How to loop through key/value object in Javascript?

var user = {};

now I want to create a setUsers() method that takes a key/value pair object and initializes the user variable.

setUsers = function(data) {
// loop and init user
}

where data is like:

234: "john", 23421: "smith", ....
373761 次浏览

就像这样:

setUsers = function (data) {
for (k in data) {
user[k] = data[k];
}
}
for (var key in data) {
alert("User " + data[key] + " is #" + key); // "User john is #234"
}

小心从对象的原型继承的属性(如果在页面上包含任何库,例如 Prototype 的旧版本,就可能会发生这种情况)。您可以使用对象的 hasOwnProperty()方法来检查这一点。在使用 for...in循环时,这通常是一个好主意:

var user = {};


function setUsers(data) {
for (var k in data) {
if (data.hasOwnProperty(k)) {
user[k] = data[k];
}
}
}