通过数组映射时检查下一个项属性

时间:2016-02-08 16:56:29

标签: javascript lodash

我目前正在通过数组进行映射,即

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中看到的那样,我需要抓住下一个项目的类型。我知道这可以使用for循环i增量,但需要在map中进行。我打算使用像lodash这样的库提出建议(我们无法在文档中找到任何内容)。

2 个答案:

答案 0 :(得分:13)

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 :(得分:1)

首先,Array.prototype.map要求您返回您未执行的映射值。

在一个简单的例子中:

const primes = [2, 3, 5, 7, 11, 13];

const primesSquared = primes.map((prime) => {
  return prime * prime;
});

Array.prototype.map有三个参数:

  • 元素:当前数组元素

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

  • 数组:整个数组

您的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"; 
  }
});

参考文献: