遍历具有索引的JavaScript对象 [英] Iterate over JavaScript object with index

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

问题描述

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

I am trying to loop over a JavaScript object in ES6.

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

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

It works fine, although when I try to use index to get the first item it returns an error in console:

Uncaught TypeError: Invalid attempt to destructure non-iterable instance

关于如何遍历带有索引的对象的任何想法?谢谢

Any ideas on how to loop over an object with index? thanks

推荐答案

这仅是对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:

Of course, you can leave out the key at any time:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆