JavaScript forEach implementation

JavaScript forEach implementation

本文关键字:implementation forEach JavaScript      更新时间:2023-09-26

我在教程网站上找到了一个forEach函数的代码片段,除了检查i是否在数组中的行之外,一切都对我来说很有意义:

    if (i in this) {       

如果我们已经有一个具有停止条件的 for 循环,为什么要打扰呢?

if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function") {
        throw new TypeError();
    }
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in this) {
            fun.call(thisp, this[i], i, this);
        }
    }
};
}

两个原因:

1. 回调突变

调用fun可能会更改数组,因为fun完全是用户定义的。所以你需要再次检查。

例:

array.forEach(function (el, i) { delete array[i + 1]; });

2. 稀疏数组

另一个问题是可能存在稀疏数组:例如

3 in ["a", "b", "c", , "e", "f"] === false
// even though
3 in ["a", "b", "c", undefined, "e", "f"] === true

在这些情况下,您不想为该索引/元素调用fun,因为该索引中没有任何内容。

["a", "b", "c", , "e", "f"].forEach(function (el, i) {
    console.log(el + " at " + i);
});
// => "a at 0" "b at 1" "c at 2" "e at 4" "f at 5"

因为数组可以有孔,因此您可以迭代长度,并且并非所有值都存在。

x = new Array()
[]
x[0] = "zero"
"zero"
x[5] = "five"
"five"
x
["zero", undefined × 4, "five"]
3 in x
false
x.length
6
for (var i = 0; i < x.length; i++) { console.log(i, i in x, x[i])}
0 true "zero"
1 false undefined
2 false undefined
3 false undefined
4 false undefined
5 true "five"