假设我们有一个像这样的对象数组:
var fruits = [ {name:"banana", weight:150},{name:"apple", weight:130},{name:"orange", weight:160},{name:"kiwi", weight:80} ]
我想遍历水果,并每次告诉当前,前一个和下一个水果的名称。我会做类似的事情:
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + item[index-1].name);
console.log("Next: " + item[index-1].name);
});
但是显然,它不适用于下一个和上一个项目...有什么主意吗?
请注意,我不想使用经典的for循环
(对于i = 0;我
非常感谢!
它不起作用,因为item不是数组,所以我们无法编写item [index-1] .name。相反,我们需要使用fruits [index-1]。此外,数组的第一个元素将没有上一项,而最后一个元素将没有下一项。以下代码段适合您。
var fruits = [{
name: "banana",
weight: 150
}, {
name: "apple",
weight: 130
}, {
name: "orange",
weight: 160
}, {
name: "kiwi",
weight: 80
}]
fruits.forEach(function(item, index) {
console.log("Current: " + item.name);
if (index > 0) {
console.log("Previous: " + fruits[index - 1].name);
}
if (index < fruits.length - 1) {
console.log("Next: " + fruits[index + 1].name);
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句