JS闭包和函数参数

JS Closure and Function Parameters

本文关键字:参数 函数 闭包 JS      更新时间:2023-09-26

以下片段来自JS和闭包上这个线程的"示例5"。或者,另一条线索也能找到我好奇的地方。

function buildList(list) {
    var result = [];
    for (var i = 0; i < list.length; i++) {
        var item = 'item' + i;
        result.push( function() {alert(item + ' ' + list[i])} );
    }
    return result;
}
function testList() {
    var fnlist = buildList([1,2,3]);
    for (var j = 0; j < fnlist.length; j++) {
        fnlist[j]();
    }
}

这个片段来自的线程表示输出为:"item3 undefined"x3。我理解为什么"item3"被打印了三次,但我不理解为什么list[i]是未定义的。

我的问题:由于list是buildList的一个参数,这是否意味着它不是result.push中匿名函数闭包的一部分?如果buildList(otherList)中有一个变量被设置为list(而匿名函数使用了otherList[i]),那么otherList[i]会在闭包中吗?(因此,输出将不是"item3 undefined"x3,而是"item3 3"x3)。

它有三个元素,所以最大有效索引是2。所以它不是打印item3 undefined,而是打印item2 undefined

原因:

因为您知道该函数每次都打印item-2字符串,所以该函数绑定到引用,而不是值。(使用即时调用函数可以避免这种情况)。

但当我穿过i < array.length时,循环停止/停止,因此i的最后更新值现在是3,索引3处的数组[1,2,3]是undefined。因此,您看到的是未定义的值。


验证:

添加console.log,如下所示

    for (var i = 0; i < list.length; i++) {
        var item = 'item' + i;
        result.push( function() {
             console.log(i);              //Prints 3 for all 3 invocation.
             alert(item + ' ' + list[i])
        } );
    }