美文网首页
JavaScript在filter的同时执行map

JavaScript在filter的同时执行map

作者: 六寸光阴丶 | 来源:发表于2021-07-18 14:36 被阅读0次

    背景

    Array.prototype.filter可以过滤数组,去掉数组中不需要的元素,Array.prototype.map可以从数组中生成新数组,但有时我们想在生成新数组的同时过滤掉一些内容,并且有时候不需要遍历全部元素,为了达到这个目的,我们设计了如下方法。

    源代码

    Array.prototype.fmap = function (fn, start = 0, end = this.length, _this = this) {
      let arr = [];
      for (let index = start; index < end; index++) {
        // 执行回调函数时绑定this
        const result = fn.call(_this, this[index], index, this);
        // 如果结果不为undefined,则将结果push进新数组
        if (result !== undefined) {
          arr.push(result);
        }
      }
      // 返回新数组
      return arr;
    };
    
    // 设置新增原型为不可枚举,不会被for...in遍历出来
    Object.defineProperty(Array.prototype, 'fmap', {
      enumerable: false
    })
    

    测试

    // 测试
    const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    const callback = item => item % 2 === 0 ? item : undefined
    const newarr = arr.fmap(callback, 0, 7);
    console.log(newarr);
    // result: [ 0, 2, 4, 6 ]
    

    相关文章

      网友评论

          本文标题:JavaScript在filter的同时执行map

          本文链接:https://www.haomeiwen.com/subject/skqapltx.html