JavaScript在filter的同时执行map

背景

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 ]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容