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
接受三个参数:
- 元素:当前数组元素
- 索引:数组中当前元素的索引
- 数组:整个数组
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
参考文献:
- 开关语句:
- 地图:
数组[index+1]
进行条件检查,那么一行代码,我就不太擅长这些。它只会检查在当前值之后是否有一个有效的元素。如果我们跳过该检查,解释程序将在我们位于最后一个元素时抛出错误。@jAndy访问数组的不存在索引不会在javascript中抛出错误。它返回undefined。