Iterate through object properties

var obj = {
    name: "Simon",
    age: "20",
    clothing: {
        style: "simple",
        hipster: false
    }
}

for(var propt in obj){
    alert(propt + ': ' + obj[propt]);
}

How does the variable propt represent the properties of the object? It's not a built-in method, or property. Then why does it come up with every property in the object?


Iterating over properties requires this additional hasOwnProperty check:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of object .

hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class.


As of JavaScript 1.8.5 you can use Object.keys(obj) to get an Array of properties defined on the object itself (the ones that return true for obj.hasOwnProperty(key) ).

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

This is better (and more readable) than using a for-in loop.

Its supported on these browsers:

  • Firefox (Gecko): 4 (2.0)
  • Chrome: 5
  • Internet Explorer: 9
  • See the Mozilla Developer Network Object.keys() 's reference for futher information.


    It's the for...in statement (MDN, ECMAScript spec).

    You can read it as " FOR every property IN the obj object, assign each property to the PROPT variable in turn".

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

    上一篇: 在Java中迭代列表的方法

    下一篇: 遍历对象属性