我尝试在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关于如何使用索引遍历对象有什么想法吗?谢谢
发布于 2017-07-22 20:24:02
这只是对jonas w的解决方案的补充。
如果您需要当前值的key:
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}`);
});
发布于 2017-07-22 14:51:02
只需计算索引:
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)=> /*...*/);https://stackoverflow.com/questions/45251605
复制相似问题