Javascript 如何在Javascript中循环键/值对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2958841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through key/value object in Javascript?
提问by Blankman
var user = {};
now I want to create a setUsers()method that takes a key/value pair object and initializes the uservariable.
现在我想创建一个setUsers()接受键/值对对象并初始化user变量的方法。
setUsers = function(data) {
// loop and init user
}
where data is like:
数据如下:
234: "john", 23421: "smith", ....
回答by Tim Down
Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty()method. This is generally a good idea when using for...inloops:
注意从对象的原型继承的属性(如果您在页面上包含任何库,例如旧版本的 Prototype,则可能会发生这种情况)。您可以使用对象的hasOwnProperty()方法来检查这一点。使用for...in循环时,这通常是一个好主意:
var user = {};
function setUsers(data) {
for (var k in data) {
if (data.hasOwnProperty(k)) {
user[k] = data[k];
}
}
}
回答by Felix
for (var key in data) {
alert("User " + data[key] + " is #" + key); // "User john is #234"
}
回答by Bialecki
Something like this:
像这样的东西:
setUsers = function (data) {
for (k in data) {
user[k] = data[k];
}
}

