探秘JavaScript中的forEach底层原理

126 阅读1分钟

在我们平时开发中使用forEach的时候可能都会发现这几个问题:

1. forEach 方法不支持处理异步函数

function test() {
    let arr = [3, 2, 1];
    arr.forEach(async item => {
        const res = await fetch('http://xxx');
        console.log(item);
    });
    console.log('end');
}
test()

期望得到的结果:

end
3
2
1

实际得到的结果可能是:

end
1
3
2

2. 给自身push不会无限循环

const arr = [1, 2, 3]
arr.forEach((item, index) => {
// 这样并不会无线循环arr
    arr.push(1)
})

还有其他很多现象,forEach好像都不像我们想的那样...

那么forEach的底层到底是怎么设计的呢?

我们来模拟实现一下forEach

Array.prototype.myForEach = function (callback) {
    // 查看参数是否为回调函数
    if (typeof callback !== 'function') {
        throw new Error(callback + 'is not a function')
    }

    // 获取数组的length
    const len = this.length
    let k = 0
    // 循环数组调用回调函数
    while (k < len) {
        if (k in this) {
            callback(this[k], k, this)
        }
        k++
    }
}

看了forEach的实现原理,我们就不难明白为什么forEach不如我们想象的那样执行了