使用索引迭代JavaScript对象

时间:2017-07-22 06:47:47

标签: javascript for-loop ecmascript-6

我正在尝试遍历ES6中的JavaScript对象。

 for (let [value, index] of object) {
    do something with rest
    if (index >= 1) {
       // do something with first item
    }
  }

它工作正常,虽然当我尝试使用索引来获取第一个项目时它会在控制台中返回错误:

Uncaught TypeError: Invalid attempt to destructure non-iterable instance

关于如何使用索引循环对象的任何想法?谢谢

2 个答案:

答案 0 :(得分:4)

这只是jonas w解决方案的补充。

如果您需要当前值的键:



const object = {a:2, b:4, c:6, d:8};

for (const [index, [key, value]] of Object.entries(Object.entries(object))) {
  console.log(`${index}: ${key} = ${value}`);
}

Object.entries(object).forEach(([key, value], index) => {
  console.log(`${index}: ${key} = ${value}`);
});




当然,您可以随时忽略key



const object = {a:2, b:4, c:6, d:8};

for (const [index, [, value]] of Object.entries(Object.entries(object))) {
  console.log(`${index}: ${value}`);
}

Object.entries(object).forEach(([, value], index) => {
  console.log(`${index}: ${value}`);
});




答案 1 :(得分:3)

只需计算索引:

var index=0;
for (let value of object) {
//do something with rest
 if (index >= 1) {
   // do something with the third and following items
 }
 index++;
}

或者如果你真的想使用对象解构(我不知道为什么)它会更复杂:

var entries=Object.entries(object);
var i=0;
entries.forEach(e=>e.push(i++));

for(let [key,value,index] of entries){
 //...
}

或:

for(let [index,value] of Object.entries(Object.values(object))){
  //...
}

但我不知道你为什么不使用简单的forEach?:

Object.values(obj).forEach((value,index)=>/*...*/);