一、写在前面
数组的forEach
方法,forEach
方法中存在两个变量,第一个变量是一个回调函数,第二个变量是this
的指向。
二、手写
Array.prototype.myForEach = function (callback, thisArg) {
let length = this.length
if (!Array.isArray(this)) throw new TypeError('this is not an array')
if (typeof callback !== 'function') throw new TypeError(callback + ' is not a function')
for (let i = 0; i < length; i++) {
callback.call(thisArg, this[i], i, this)
}
}