使用for in 循环Object会有个问题,会loop来自prototype的属性,使用的时候要小心;
1 2 3 4 5 6 7 8 9 10 11 12 13
| for (var key in validation_messages) { if (!validation_messages.hasOwnProperty(key)) continue;
var obj = validation_messages[key]; for (var prop in obj) { if(!obj.hasOwnProperty(prop)) continue;
alert(prop + " = " + obj[prop]); } }
|
或者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
|
参考资料
https://stackoverflow.com/questions/921789/how-to-loop-through-a-plain-javascript-object-with-the-objects-as-members