使用索引迭代JavaScript对象

plupiseo  于 2023-01-04  发布在  Java
关注(0)|答案(4)|浏览(107)

我尝试在ES6中循环遍历JavaScript对象。

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

它工作正常,尽管当我尝试使用index获取第一项时,它在控制台中返回了一个错误:

Uncaught TypeError: Invalid attempt to destructure non-iterable instance

关于如何循环遍历一个带index的对象有什么想法吗?谢谢

fykwrbwg

fykwrbwg1#

  • 这只是乔纳斯·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}`);
});
w8biq8rn

w8biq8rn2#

只需计算指数:

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

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

let entries = Object.entries(object);

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

或:

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

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

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

r7s23pms3#

indexkey

for (const [index, key] of Object.keys(object).entries()) {
  // ...
}

indexvalue

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

indexkeyvalue

for (const [index, [key, value]] of Object.entries(object).entries()) {
  // ...
}
x8diyxa7

x8diyxa74#

只需计算指数:

let index = 0;
for (let value of object) {
  if (index === 1) {
    // do something with idx 1
  }
  // do something with the rest...
  index++;
}

相关问题