How to print values of a object in JavaScript?

This question already has an answer here:

  • How to loop through a plain JavaScript object with the objects as members? 17 answers

  • var friends = {
        bill:
        {
            firstName: "A",
            lastName: "C",        
            number: "999",
        },
        print: function () {
            for (var p in this.bill)
                console.log(p + ' ' + this.bill[p]);
        }
    };
    

    这段代码将会打印出来,是你需要的吗?

    friends.print();
    

    If you'd like to print only the members of within friends.bill , you might want to use a for..in loop, for example:

    for(var p in friends.bill) 
        console.log(p + ": " + friends.bill[p])
    

    Which will print this in the console:

    firstName: A VM579:3
    lastName: C VM579:3
    number: 999 
    

    I'm going to make a suggestion that might make your coding a little easier. Instead of using an object to contain a list of friends, use an array instead. An array is a list after all, and Javascript comes with some really useful array functions that can help you in the long run.

    var friends = [
      {
       name: 'Bill Z',
       firstName: "Bill",
       lastName: "X",
       number: "999",
      },
      {
       name: 'Sam Y',
       firstName: "Sam",
       lastName: "Y",
       number: "999",
      }    
    ];
    

    To get the list of friends you might use a couple of loops; one to loop over the list of objects, and one to loop over the properties of each object:

    function listFriends() {
      for (var i = 0, l = friends.length; i < l; i++) {
        for (var p in friends[i]) {
            console.log(p + ': ' + friends[i][p]);
        }
      }
    }
    

    Or to get HTML out:

    function listFriends() {
      var html = '';
      for (var i = 0, l = friends.length; i < l; i++) {
        html += '<b>' + friends[i].firstName + '</b><br/>';
        for (var p in friends[i]) {
            html += p.toUpperCase() + ': ' + friends[i][p] + '<br/>';
        }
      }
      return html;
    }
    

    You might also like to access the list of friends to find one in particular. In this example I use filter .

    function getFriend(prop, value) {
      return friends.filter(function (obj) {
        return obj[prop] === value;
      });
    }
    
    console.log(getFriend('firstName', 'Sam')) // { name="Sam Y", firstName="Sam", lastName="Y"}
    

    Fiddle.

    Hopefully you'll find some of this useful.

    链接地址: http://www.djcxy.com/p/52006.html

    上一篇: 如何通过嵌套对象循环

    下一篇: 如何在JavaScript中打印对象的值?