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

当前回答

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

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

其他回答

你可以这样做

Var sources = []; 图像。映射(函数(img) { 如果(img.src.split (' . ') .pop () ! = = json){/ /如果扩展不是. json sources.push (img.src);//只推有效值 } });

我认为从数组中跳过一些元素的最简单方法是使用filter()方法。

通过使用这个方法(ES5)和ES6语法,你可以在一行中编写你的代码,这将返回你想要的:

Let images = [{src: 'img.png'}, {src: 'j1. png'}。Json '}, {src: 'img.png'}, {src: ' Json . Json '}]; Let sources = images。过滤(img => img.src.slice(-4) != 'json')。Map (img => img.src); console.log(来源);

先.filter()它:

var sources = images.filter(function(img) {
  if (img.src.split('.').pop() === "json") {
    return false; // skip
  }
  return true;
}).map(function(img) { return img.src; });

如果你不想这样做,这并不是不合理的,因为它有一些成本,你可以使用更通用的.reduce()。你通常可以用.reduce来表示.map():

someArray.map(function(element) {
  return transform(element);
});

可以写成

someArray.reduce(function(result, element) {
  result.push(transform(element));
  return result;
}, []);

因此,如果你需要跳过元素,你可以使用.reduce()轻松完成:

var sources = images.reduce(function(result, img) {
  if (img.src.split('.').pop() !== "json") {
    result.push(img.src);
  }
  return result;
}, []);

在该版本中,来自第一个示例的.filter()中的代码是.reduce()回调的一部分。只有在过滤操作保留结果数组的情况下,才会将图像源推入结果数组。

更新-这个问题得到了很多关注,我想补充以下澄清意见。作为一个概念,.map()的目的正是“map”的意思:根据某些规则将一个值列表转换为另一个值列表。就像某些国家的纸质地图如果完全缺少几个城市就会显得很奇怪一样,从一个列表映射到另一个列表只有在有1对1的结果值集时才有意义。

我并不是说,从一个旧列表中创建一个新列表并排除一些值是没有意义的。我只是试图说明.map()只有一个简单的意图,即创建一个与旧数组长度相同的新数组,只是使用由旧值转换形成的值。

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

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

如果它在一行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);