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

其他回答

我使用foreach():

var sources = [];

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

注:我否定了你的逻辑。

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

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'];

下面是@theprtk提供的代码的更新版本。这是一个小清理,以显示广义版本,同时有一个例子。

注:我想把这句话作为评论加到他的帖子里,但我还没有足够的声誉

/**
 * @see http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
 * @description functions that transform reducing functions
 */
const transduce = {
  /** a generic map() that can take a reducing() & return another reducing() */
  map: changeInput => reducing => (acc, input) =>
    reducing(acc, changeInput(input)),
  /** a generic filter() that can take a reducing() & return */
  filter: predicate => reducing => (acc, input) =>
    predicate(input) ? reducing(acc, input) : acc,
  /**
   * a composing() that can take an infinite # transducers to operate on
   *  reducing functions to compose a computed accumulator without ever creating
   *  that intermediate array
   */
  compose: (...args) => x => {
    const fns = args;
    var i = fns.length;
    while (i--) x = fns[i].call(this, x);
    return x;
  },
};

const example = {
  data: [{ src: 'file.html' }, { src: 'file.txt' }, { src: 'file.json' }],
  /** note: `[1,2,3].reduce(concat, [])` -> `[1,2,3]` */
  concat: (acc, input) => acc.concat([input]),
  getSrc: x => x.src,
  filterJson: x => x.src.split('.').pop() !== 'json',
};

/** step 1: create a reducing() that can be passed into `reduce` */
const reduceFn = example.concat;
/** step 2: transforming your reducing function by mapping */
const mapFn = transduce.map(example.getSrc);
/** step 3: create your filter() that operates on an input */
const filterFn = transduce.filter(example.filterJson);
/** step 4: aggregate your transformations */
const composeFn = transduce.compose(
  filterFn,
  mapFn,
  transduce.map(x => x.toUpperCase() + '!'), // new mapping()
);

/**
 * Expected example output
 *  Note: each is wrapped in `example.data.reduce(x, [])`
 *  1: ['file.html', 'file.txt', 'file.json']
 *  2:  ['file.html', 'file.txt']
 *  3: ['FILE.HTML!', 'FILE.TXT!']
 */
const exampleFns = {
  transducers: [
    mapFn(reduceFn),
    filterFn(mapFn(reduceFn)),
    composeFn(reduceFn),
  ],
  raw: [
    (acc, x) => acc.concat([x.src]),
    (acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src] : []),
    (acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src.toUpperCase() + '!'] : []),
  ],
};
const execExample = (currentValue, index) =>
  console.log('Example ' + index, example.data.reduce(currentValue, []));

exampleFns.raw.forEach(execExample);
exampleFns.transducers.forEach(execExample);

先.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()只有一个简单的意图,即创建一个与旧数组长度相同的新数组,只是使用由旧值转换形成的值。