我有一个对象 x
有一堆属性。其中一个属性是 heroes
,它的值为对象数组。我有兴趣遍历 heroes
的对象数组并从中访问特定属性。
代码如下:
x = {id: "prim1", description: "planner", heroes: [{name: "arrow", universe: "dc"}, {name: "shields", universe: "marvel"}]};
我写了一个简单的for循环
来实现我想要的如下:
for (let idx = 0; idx < x.heroes.length; idx++) {
console.log(x.heroes[idx].universe);
}
我如何使用最新的 ES6 的 for of
循环实现同样的功能?
谢谢。
最佳答案
这是使用 for of 的解决方案loop ,你只需要使用这个结构调用可迭代元素:
for (variable of iterable) {
console.log(variable)
}
在每次迭代中,您可以获得当前变量。
x = {
id: "prim1",
description: "planner",
heroes: [{
name: "arrow",
universe: "dc"
}, {
name: "shields",
universe: "marvel"
}]
};
for (let idx = 0; idx < x.heroes.length; idx++) {
console.log(x.heroes[idx].universe);
}
for (let o of x.heroes) {
console.log(o.universe);
}
关于javascript - 在 javascript 中使用 for of 循环迭代对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105034/