关于javascript:手写实现一个forEach方法和用reduce实现map

8次阅读

共计 1641 个字符,预计需要花费 5 分钟才能阅读完成。

实现一个 forEach 办法

forEach() 办法对数组的每个元素执行一次给定的函数。

arr.forEach(function(currentValue, currentIndex, arr) {}, thisArg)

//currentValue  必须。以后元素
//currentIndex  可选。以后元素的索引
//arr           可选。以后元素所属的数组对象。//thisArg       可选参数。当执行回调函数时,用作 this 的值。
Array.prototype._forEach = function(fn, thisArg) {if (typeof fn !== 'function') throw "参数必须为函数";
    if(!Array.isArray(this)) throw "只能对数组应用 forEach 办法";
    let arr = this;
    for(let i=0; i<arr.length; i++) {fn.call(thisArg, arr[i], i, arr)
    }
}

// test
let arr = [1,2,3,4,5];
arr._forEach((item, index) => {console.log(item, index);
})

// test thisArg

function Counter() {
    this.sum = 0;
    this.count = 0;
}
// 因为 thisArg 参数(this)传给了 forEach(),每次调用时,它都被传给 callback 函数,作为它的 this 值。Counter.prototype.add = function (array) {array._forEach(function (entry) {
        this.sum += entry;
        ++this.count;
    }, this);
      // ^---- Note
};

const obj = new Counter();
obj.add([2, 5, 9]);

console.log(obj.count); // 3 === (1 + 1 + 1)
console.log(obj.sum);  // 16 === (2 + 5 + 9)

用 reduce 实现 map

reduce 是一个累加办法,是对数组累积执行回调函数,返回最终计算结果。

array.reduce(function(total, currentValue, currentIndex, arr){}, initialValue);

//total 必须。初始值, 或者计算完结后的返回值。//currentValue  必须。以后元素
//currentIndex  可选。以后元素的索引
//arr   可选。以后元素所属的数组对象。//initialValue 可选。传递给函数的初始值 

map 是遍历数组的每一项,并执行回调函数的操作,返回一个对每一项进行操作后的新数组。

array.map(function(currentValue,index,arr), thisArg);//currentValue  必须。以后元素的值
//index 可选。以后元素的索引值
//arr   可选。以后元素属于的数组对象
//thisArg 可选。对象作为该执行回调时应用,传递给函数,用作 "this" 的值。如果省略了 thisArg,或者传入 null、undefined,那么回调函数的 this 为全局对象。

用 reduce 实现 map 办法

Array.prototype.myMap = function(fn, thisArg){var res = [];
    thisArg = thisArg || [];
    this.reduce(function(pre, cur, index, arr){res.push(fn.call(thisArg, cur, index, arr));
  }, []);
  return res;
}
var arr = [2,3,1,5];
arr.myMap(function(item,index,arr){console.log(item,index,arr);
})
let res = arr.myMap(v => v * 2);
console.log(res); // [4,6,2,10]
正文完
 0