Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - 如何在Javascript中循环键入/值对象? [重复](How to loop through key/value object in Javascript? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

var user = {};

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

(现在我想创建一个setUsers()方法,它接受一个键/值对对象并初始化user变量。)

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

where data is like:

(数据如下:)

234: "john", 23421: "smith", ....
  ask by Blankman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

(注意从对象原型继承的属性(如果您在页面上包含任何库,可能会发生这种情况,例如旧版本的Prototype)。)

You can check for this by using the object's hasOwnProperty() method.

(您可以使用对象的hasOwnProperty()方法来检查这一点。)

This is generally a good idea when using for...in loops:

(当使用for...in循环时,这通常是一个好主意:)

var user = {};

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...