How to skip over an element in .map()?

前端 未结 16 2025
余生分开走
余生分开走 2020-11-27 09:26

How can I skip an array element in .map?

My code:

var sources = images.map(function (img) {
    if(img.src.split(\'.\').pop() === \"json         


        
16条回答
  •  隐瞒了意图╮
    2020-11-27 09:52

    Here's a fun solution:

    /**
     * Filter-map. Like map, but skips undefined values.
     *
     * @param callback
     */
    function fmap(callback) {
        return this.reduce((accum, ...args) => {
            let x = callback(...args);
            if(x !== undefined) {
                accum.push(x);
            }
            return accum;
        }, []);
    }
    

    Use with the bind operator:

    [1,2,-1,3]::fmap(x => x > 0 ? x * 2 : undefined); // [2,4,6]
    

提交回复
热议问题