Javascript forEach()通过数组:如何获取上一项和下一项

Javascript forEach() through an array: how to get the previous and next item?

本文关键字:一项 获取 forEach 数组 Javascript 何获取      更新时间:2023-09-26

假设我们有一个对象数组,如:

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);
});

但很明显,它不适用于下一项和前一项。。。知道吗?

请注意,我不想使用经典的循环

(对于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);
    }
});
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));
});

对于第一个和最后一个项目,您可以记录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);
    });
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);
  }
});