JavaScript forEach实现

wor*_*138 6 javascript

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

    if (i in this) {       
Run Code Online (Sandbox Code Playgroud)

如果我们已经有一个具有停止条件的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);
        }
    }
};
}
Run Code Online (Sandbox Code Playgroud)

Dom*_*nic 7

两个原因:

1.回调变异

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

例:

array.forEach(function (el, i) { delete array[i + 1]; });
Run Code Online (Sandbox Code Playgroud)

2.稀疏数组

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

3 in ["a", "b", "c", , "e", "f"] === false
// even though
3 in ["a", "b", "c", undefined, "e", "f"] === true
Run Code Online (Sandbox Code Playgroud)

在这些情况下,您不希望调用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"
Run Code Online (Sandbox Code Playgroud)