Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 如何遍历JavaScript对象?(How to iterate over a JavaScript object?)

I have an object in JavaScript:

(我在JavaScript中有一个对象:)

{
    abc: '...',
    bca: '...',
    zzz: '...',
    xxx: '...',
    ccc: '...',
    // ...
}

I want to use a for loop to get its properties.

(我想使用一个for循环来获取其属性。)

And I want to iterate it in parts (not all object properties at once).

(而且我想对其进行迭代(不是一次所有对象属性)。)

With a simple array I can do it with a standard for loop:

(通过一个简单的数组,我可以使用标准的for循环来做到这一点:)

for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last

But how to do it with objects?

(但是如何处理对象呢?)

  ask by nkuhta translate from so

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

1 Answer

0 votes
by (71.8m points)

For most objects, use for .. in :

(对于大多数对象, for .. in :)

for (let key in yourobject) {
  console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

(使用ES6,如果同时需要键和值,请执行)

for (let [key, value] of Object.entries(yourobject)) {
    console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

(为了避免记录继承的属性,请使用hasOwnProperty进行检查:)

for (let key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}

You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {} ).

(如果您使用的是简单对象(例如,您使用{}对象),则在对键进行迭代时无需检查hasOwnProperty)

This MDN documentation explains more generally how to deal with objects and their properties.

(该MDN文档更一般地说明了如何处理对象及其属性。)

If you want to do it "in chunks", the best is to extract the keys in an array.

(如果要“分块”执行,最好的方法是将键提取到数组中。)

As the order isn't guaranteed, this is the proper way.

(由于不能保证顺序,这是正确的方法。)

In modern browsers, you can use

(在现代浏览器中,您可以使用)

let keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

(为了更加兼容,您最好这样做:)

 let keys = [];
 for (let key in yourobject) {      
     if (yourobject.hasOwnProperty(key)) keys.push(key);
 }

Then you can iterate on your properties by index: yourobject[keys[i]] :

(然后,您可以通过索引迭代属性: yourobject[keys[i]] :)

for (let i=300; i < keys.length && i < 600; i++) { 
   console.log(keys[i], yourobject[keys[i]]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...