js 实现forEach

手写foreach

/**
 * forEach(cb,thisArg) 
 * cb : (value: any, index: number, array: any[]) => void, thisArg?: any): void
 * 接受第二个参数thisArg,只是定制forEach中this的指向, 并不影响传给回调函数中的三个参数
 */
Array.prototype._forEach = function (cb, thisArg) {
    if (typeof cb !== 'function') {
        throw 'the parameter cb must be a function'
    }
    if (!Array.isArray(this)) {
        throw 'function _forEach must used by Array'
    }
    const arr = this
    for (let index = 0; index < arr.length; index++) {
        const v = arr[index];
        cb.apply(thisArg, [v, index, arr])
    }
}

Array(3).fill()._forEach(function (e) {
    console.log(arguments,this);
})
posted @ 2022-01-25 12:30  IslandZzzz  阅读(175)  评论(0编辑  收藏  举报