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
279 views
in Technique[技术] by (71.8m points)

javascript - 如何遍历或枚举JavaScript对象?(How do I loop through or enumerate a JavaScript object?)

I have a JavaScript object like the following:

(我有一个如下的JavaScript对象:)

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Now I want to loop through all p elements ( p1 , p2 , p3 ...) And get their keys and values.

(现在,我想遍历所有p元素( p1p2p3 ...),并获取它们的键和值。)

How can I do that?

(我怎样才能做到这一点?)

I can modify the JavaScript object if necessary.

(我可以根据需要修改JavaScript对象。)

My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval .

(我的最终目标是遍历一些键值对,如果可能的话,我想避免使用eval 。)

  ask by Tanmoy translate from so

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

1 Reply

0 votes
by (71.8m points)

You can use the for-in loop as shown by others.

(您可以使用for-in循环,如其他人所示。)

However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

(但是,您还必须确保获得的键是对象的实际属性,而不是来自原型。)

Here is the snippet:

(这是代码段:)

 var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; for (var key in p) { if (p.hasOwnProperty(key)) { console.log(key + " -> " + p[key]); } } 

For-of with Object.keys() alternative:

(用Object.keys()替代:)

 var p = { 0: "value1", "b": "value2", key: "value3" }; for (var key of Object.keys(p)) { console.log(key + " -> " + p[key]) } 

Notice the use of for-of instead of for-in , if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object's own properties without the whole prototype-chain properties

(请注意,使用for-of而不是for-in ,如果不使用它将在命名属性上返回undefined,并且Object.keys()确保仅使用对象自己的属性,而不使用整个原型链属性)


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

...