【问题标题】:When mapping through an array check next item property通过数组进行映射时,检查下一项属性
【发布时间】:2016-05-18 10:23:50
【问题描述】:

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

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 循环,但需要在地图中进行。我愿意接受使用 lodash 之类的库的建议(在文档中找不到任何内容)。

【问题讨论】:

  • 为什么受限于地图功能?
  • 你可以在映射之前反转数组,那么前一个元素实际上就是下一个元素。不过,这似乎是一个愚蠢的想法,当使用 for 循环时会进行额外的计算

标签: javascript lodash


【解决方案1】:

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

【讨论】:

  • 你能解释一下如果条件检查 array[index+1] 的一个班轮,我不太擅长这些。
  • 它只会检查当前元素之后是否有有效元素。如果我们跳过该检查,如果我们在最后一个元素处,解释器将抛出错误。
  • @jAndy 访问不存在的数组索引不会在 javascript 中引发错误。它返回未定义。
  • 如果使用了void 函数,请将.map((content) => {...}) 更改为.forEach((content) => {...})。正如 Ashwin Balamohan 在他的回答中提到的那样,map 必须返回数组。
【解决方案2】:

首先,Array.prototype.map 要求您返回映射值,而您没有这样做。

举个简单的例子:

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

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

Array.prototype.map 接受三个参数:

  • element:当前数组元素

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

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 2022-07-25
    • 2021-07-06
    • 1970-01-01
    • 2011-09-11
    相关资源
    最近更新 更多