当遍历数组时,检查下一个元素的属性。

17

我目前正在遍历一个数组,即:

contents.map((content) => {
 switch(content.type) {
   case: 1
     console.log("type is one and next type is ..");
   case: 2
     console.log("type is two")
 }
})

如您所见,在案例1中,我需要获取下一个项的类型。我知道可以使用带有i增量的for循环实现,但需要在map内部执行。我愿意尝试使用类似lodash这样的库(在文档中找不到任何信息)。


你为什么局限于使用map函数? - Lee Brindley
你可以在映射之前反转数组,这样前一个元素实际上就是下一个元素。不过这似乎是个愚蠢的想法,因为这会增加额外的计算量,而使用for循环就可以解决问题。 - Lee Brindley
2个回答

42

Array.prototype.map 实际上会使用3个参数调用它的回调函数:

currentValue // current element
index // current index
array // original array

这意味着您当然可以在回调函数中通过其索引访问数组。例如:

contents.map((content, index, array) => {
    switch(content.type) {
        case 1:
            console.log("type is one and next type is: ", array[index+1] ? array[index+1].type : 'empty');
            break;
        case 2:
            console.log("type is two")
            break;
    }
});

示例:https://jsfiddle.net/z1sztd58/ 参考资料:MDN


1
你能解释一下那个一行代码的条件检查array[index+1]吗?我不太擅长这种写法。 - Ilja
1
它只会检查当前元素后面是否有有效的元素。如果我们跳过这个检查,解释器将在我们到达最后一个元素时抛出错误。 - jAndy
3
在 JavaScript 中访问不存在的数组索引不会抛出错误,而是返回 undefined。 - Nicolas Del Valle
1
如果使用了void函数,请将.map((content) => {...})更改为.forEach((content) => {...})。正如Ashwin Balamohan在他的答案中提到的那样,map必须返回数组。 - Enrique René

3
首先,Array.prototype.map 要求你返回已映射的值,而你没有这样做。
举个简单的例子:
const primes = [2, 3, 5, 7, 11, 13];

const primesSquared = primes.map((prime) => {
  return prime * prime;
});
Array.prototype.map接受三个参数:
  • element:当前数组元素

  • index:当前元素在数组中的索引

  • array:整个数组

此外,您的switch语句存在语法错误。请注意下面示例中case语句中:的位置。
您可以使用以下代码来实现您想要的功能:
const newArray = oldArray.map((elem, index, array) => {
  switch(elem.type) {
    case 1:
      return "something";
    case 2:
      return "something else";
    default:
      return "default value";
  }
});

不使用switch语句,你仍然可以轻松实现你想要的功能:

const newArray = oldArray.map((elem, index, array) => {
  if (index+1 < array.length && elem < array[index+1]) { //ensure you're not at the end of the array before checking your condition
    return "something";
  } else {
    return "something else"; 
  }
});

参考文献:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接