如何循环遍历JavaScript对象中的所有成员,包括作为对象的值?
例如,我如何循环(分别访问“your_name”和“your_message”)?
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
有很多方法可以遍历对象。请查看以下示例。
var obj = {'name':'John Doe','email':'johndoe@example.com'}
方法1
var keys = Object.keys(obj)
for(var i= 0; i < keys.length;i++){
console.log(keys[i]+ ': ' + obj[keys[i]])
}
方法2
for(var key in obj){
console.log(key+': '+ obj[key])
}
方法3
Object.keys(obj).forEach(function (key) {
console.log(key+ ': ' + obj[key])
})
每个2
(在此处找到):
var lunch = {
sandwich: 'ham',
age: 48,
};
lunch.forEach2(function (item, key) {
console.log(key);
console.log(item);
});
代码:
if (!Object.prototype.forEach2) {
Object.defineProperty(Object.prototype, 'forEach2', {
value: function (callback, thisArg) {
if (this == null) {
throw new TypeError('Not an object');
}
thisArg = thisArg || window;
for (var key in this) {
if (this.hasOwnProperty(key)) {
callback.call(thisArg, this[key], key, this);
}
}
}
});
}