本文介绍了如何遍历 JavaScript 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JavaScript 中有一个对象:

I have an object in JavaScript:

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

我想使用 for 循环来获取其属性.我想分部分迭代它(不是一次所有的对象属性).

I want to use a for loop to get its properties. And I want to iterate it in parts (not all object properties at once).

使用一个简单的数组,我可以使用标准的 for 循环来实现:

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

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

但是如何处理对象呢?

推荐答案

对于大多数对象,使用 for .. in :

For most objects, use for .. in :

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

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

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

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

为避免记录继承的属性,请检查hasOwnProperty :

To avoid logging inherited properties, check with hasOwnProperty :

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

如果您使用的是一个简单的对象(例如您使用 {} 自己制作的对象),则在迭代键时不需要检查 hasOwnProperty).

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

此 MDN 文档 更一般地解释了如何处理对象及其属性.

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

如果你想分块"进行,最好的方法是提取数组中的键.由于不能保证顺序,这是正确的方法.在现代浏览器中,您可以使用

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);
 }

然后你可以通过索引迭代你的属性:yourobject[keys[i]] :

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

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

这篇关于如何遍历 JavaScript 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:27