我如何在。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"]

当前回答

如果它在一行ES5/ES6中为空或未定义

//will return array of src 
images.filter(p=>!p.src).map(p=>p.src);//p = property


//in your condition
images.filter(p=>p.src.split('.').pop() !== "json").map(p=>p.src);

其他回答

回答无多余的边缘情况:

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

从2019年开始,Array.prototype.flatMap是一个很好的选择。

images.flatMap(({src}) => src.endsWith('.json') ? [] : src);

中数:

flatMap可以作为一种添加和删除项目的方法(修改 项目数目)在一个地图。换句话说,它允许您进行映射 多项对多项(通过分别处理每个输入项), 而不是总是一对一。在这个意义上,它就像 filter的反义词。只需返回一个1元素的数组来保存该项, 用于添加项的多元素数组,或用于删除项的0元素数组 的项目。

下面是一个实用工具方法(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"]

我使用foreach():

var sources = [];

images.forEach(function (img) {
    if(img.src.split('.').pop() !== "json"){ // if extension is .json
        sources.push(img);
    }
});

注:我否定了你的逻辑。

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

/**
 * 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]