[英]Javascript forEach() through an array: how to get the previous and next item?
假設我們有一系列對象,例如:
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; i
非常感謝!
它不起作用因為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);
}
});
對於第一個和最后一個項目,您可以記錄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);
});
選項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);
});
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));
});
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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.