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

当前回答

回答无多余的边缘情况:

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

其他回答

回答无多余的边缘情况:

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

你可以这样做

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

你可以使用map()方法的after。例如在你的例子中,filter()方法:

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

过滤方法:

const sourceFiltered = sources.filter(item => item)

然后,只有现有的项在新数组sourceFiltered中。

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

你可以像这样使用map + 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(x => x !== null);