我如何在。map中跳过数组元素?

我的代码:

var sources = images.map(function (img) {
    if(img.src.split('.').pop() === "json"){ // if extension is .json
        return null; // skip
    }
    else{
        return img.src;
    }
});

这将返回:

["img.png", null, "img.png"]

当前回答

为什么不直接使用forEach循环?

Let arr = ['a', 'b', 'c', 'd', 'e']; Let filtered = []; 加勒比海盗。forEach(x => { If (!x.includes('b')) filter .push(x); }); console.log(过滤)/ /过滤= = = [' a ', ' c ', ' d ', ' e '];

或者更简单的使用过滤器:

const arr = ['a', 'b', 'c', 'd', 'e'];
const filtered = arr.filter(x => !x.includes('b')); // ['a','c','d','e'];

其他回答

为了推断Felix Kling的评论,你可以像这样使用.filter():

var sources = images.map(function (img) {
  if(img.src.split('.').pop() === "json") { // if extension is .json
    return null; // skip
  } else {
    return img.src;
  }
}).filter(Boolean);

这将从.map()返回的数组中删除错误值。

你可以进一步简化如下:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() !== "json") { // if extension is .json
    return img.src;
  }
}).filter(Boolean);

甚至可以使用箭头函数、对象解构和&&操作符作为一行代码:

var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);

下面是一个实用工具方法(ES5兼容),它只映射非空值(隐藏reduce调用):

函数mapNonNull(arr, cb) { 加勒比海盗。Reduce(函数(累加器,值,索引,arr) { Var结果= cb。调用(null, value, index, arr); If (result != null) { accumulator.push(结果); } 返回蓄电池; },[]); } var result = mapNonNull(["a", "b", "c"],函数(值){ 返回值=== "b" ?Null:值;//排除"b" }); console.log(结果);// ["a", "c"]

const arr = [0,1, ", undefined, false, 2, undefined, null,, 3, NaN]; const filtered = arr.filter(Boolean); console.log(过滤); /* 输出:[1,2,3] * /

回答无多余的边缘情况:

const thingsWithoutNulls = things.reduce((acc, thing) => {
  if (thing !== null) {
    acc.push(thing);
  }
  return acc;
}, [])

这里有一个有趣的解决方案:

/**
 * Filter-map. Like map, but skips undefined values.
 *
 * @param callback
 */
function fmap(callback) {
    return this.reduce((accum, ...args) => {
        const x = callback(...args);
        if(x !== undefined) {
            accum.push(x);
        }
        return accum;
    }, []);
}

与绑定操作符一起使用:

[1,2,-1,3]::fmap(x => x > 0 ? x * 2 : undefined); // [2,4,6]