我如何在。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()方法。

通过使用这个方法(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(来源);

其他回答

回答无多余的边缘情况:

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

我使用foreach():

var sources = [];

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

注:我否定了你的逻辑。

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

你可以这样做

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

为了推断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);