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

Ilj*_*lja 10 javascript lodash

我目前正在通过数组映射ie

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

正如你在案例1中看到的那样,我需要抓住下一个项目的类型.我知道这可以使用for循环i增量,但需要在map中进行.我很乐意使用像lodash这样的库(无法在文档中找到任何内容).

jAn*_*ndy 17

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

currentValue // current element
index // current index
array // original array
Run Code Online (Sandbox Code Playgroud)

这意味着您当然可以通过回调例程中的索引访问数组.例如:

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

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

  • @jAndy 访问不存在的数组索引不会在 javascript 中引发错误。它返回未定义。 (3认同)