nad*_*dir 3 javascript arrays foreach loops
假设我们有一系列对象,例如:
var fruits = [ {name:"banana", weight:150},{name:"apple", weight:130},{name:"orange", weight:160},{name:"kiwi", weight:80} ]
Run Code Online (Sandbox Code Playgroud)
我想迭代水果,并告诉每一次当前,前一个和下一个水果的名称.我会做的事情如下:
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + item[index-1].name);
console.log("Next: " + item[index-1].name);
});
Run Code Online (Sandbox Code Playgroud)
但显然它不适用于下一个和之前的项目......任何想法?
请注意,我不想使用经典的for循环
(对于i = 0; i
非常感谢!
Neh*_*ala 14
它不起作用因为item不是数组所以我们不能写item [index-1] .name.相反,我们需要使用水果[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);
}
});
Run Code Online (Sandbox Code Playgroud)
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);
}
});
Run Code Online (Sandbox Code Playgroud)
对于第一项和最后一项,您可以记录 END,也可以将其设为轮播。
选项 1:标记开始和结束:
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + (0 == index)? "START" : fruits[index-1].name);
console.log("Next: " + (fruits.length - 1 == index)? "END" : fruits[index+1].name);
});
Run Code Online (Sandbox Code Playgroud)
选项 2:轮播
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + (0 == index)? fruits[fruits.length - 1].name : fruits[index-1].name);
console.log("Next: " + (fruits.length - 1 == index)? fruits[0].name : fruits[index+1].name);
});
Run Code Online (Sandbox Code Playgroud)
ForEach循环中的回调函数接受数组作为第三个参数:
fruits.forEach((item, index, arr) => {
console.log("Current: " + item.name);
console.log("Previous: " + ((0 === index)? "START" : arr[index-1].name));
console.log("Next: " + ((arr.length - 1 === index)? "END" : arr[index+1].name));
});
Run Code Online (Sandbox Code Playgroud)