背景
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 ]
网友评论