es6中对象的结构键,值和索引

问题描述 投票:0回答:1

您可以在forEach中分解对象的键,值和索引吗?

我了解解构键和值的样子:

Object.entries(obj).forEach(([key, value]) => {
  ...
});

但是我希望也能破坏索引。

我的尝试:

Object.entries(obj).forEach((entry, index) => {
    const [key, value] = entry;
    ...
});

但不确定是否有更好的方法。我知道这是一个非常基本的问题,但感谢您的帮助!

javascript object ecmascript-6 destructuring
1个回答
2
投票

只需在解构第一个参数后通常列出索引参数:

Object.entries(obj).forEach(([key, value], index) => {

const obj = {
  foo: 'val'
};

Object.entries(obj).forEach(([key, value], index) => {
  console.log(key, value, index);
});
© www.soinside.com 2019 - 2024. All rights reserved.