Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过数组映射时,请检查下一项属性_Javascript_Lodash - Fatal编程技术网

Javascript 通过数组映射时,请检查下一项属性

Javascript 通过数组映射时,请检查下一项属性,javascript,lodash,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中看到的,我需要抓取下一个项目的类型。我知道这可以使用带有I增量的for循环,但需要在映射内完成。我愿意接受使

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

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等库的建议(在文档中找不到任何内容)

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;
    }
});
例如:
参考:

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

在一个简单的例子中:

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

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

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

  • 元素:当前数组元素

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

  • 数组:整个数组

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"; 
  }
});
const newArray=oldArray.map((元素、索引、数组)=>{
如果(index+1
参考文献:

  • 开关语句:

  • 地图:


为什么要使用map函数?可以在映射之前反转数组,那么前一个元素实际上就是下一个元素。这似乎是一个愚蠢的想法,当一个for循环可以做额外的计算时,你能解释一下,如果对
数组[index+1]
进行条件检查,那么一行代码,我就不太擅长这些。它只会检查在当前值之后是否有一个有效的元素。如果我们跳过该检查,解释程序将在我们位于最后一个元素时抛出错误。@jAndy访问数组的不存在索引不会在javascript中抛出错误。它返回undefined。