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

前端 未结 16 2008
余生分开走
余生分开走 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 10:09

    Here's a utility method (ES5 compatible) which only maps non null values (hides the call to reduce):

    function mapNonNull(arr, cb) {
        return arr.reduce(function (accumulator, value, index, arr) {
            var result = cb.call(null, value, index, arr);
            if (result != null) {
                accumulator.push(result);
            }
    
            return accumulator;
        }, []);
    }
    
    var result = mapNonNull(["a", "b", "c"], function (value) {
        return value === "b" ? null : value; // exclude "b"
    });
    
    console.log(result); // ["a", "c"]

提交回复
热议问题