【问题标题】:Weird closure behavior with loop带有循环的奇怪关闭行为
【发布时间】:2015-07-16 07:27:59
【问题描述】:

所以我已经在 SO 上学到了很多关于闭包的知识。

但我还是找到了一个我无法向自己解释的例子:

       function buildList(list){
            var result = [];
            for(var i = 0; i < list.length; i++) {
                var item = "item: " + list[i] + " i's value: " + i;  //i has the value of 2 here, but why?
                result.push( function(){document.write(item + ", list[i]:" + list[i] + ", i's value in the anonymous function:" + i + "<br>")});
            } //i = 3 here
            return result;
        }

        function testList(){
            var testTheList = buildList([1,2,3]);
            for (var j = 0; j < testTheList.length; j++) {
                testTheList[j]();
            }
        }

        testList();

正如我所期望的那样,当我执行 testList() 时,我应该是 3。

但结果是:

item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3

item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3

item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3

为什么是 i 用于 var item => 2 和 i 在匿名函数 => 3 中?正如我所读到的,闭包创建了新的执行环境,但我不应该为闭包提供相同的值吗?

编辑

这不是JavaScript closure inside loops – simple practical example的重复,我不想知道,如何创建一个新的执行环境。

我想知道为什么同一个变量 i(循环的)的值在同一个作用域内不同?

【问题讨论】:

    标签: javascript closures


    【解决方案1】:

    当您将新函数添加到 result 列表时,它会引用 item 变量和 i 计数器。在buildList 函数内的循环期间,您不会创建几个item 变量,而是覆盖现有的变量,在buildList 函数的末尾,item 和i 变量的执行值如下所示:

    • 3
    • “项目:3 i的值:2”

    而list[i] 是undefined,因为您的列表长度为3,您没有list[3] 项目。因此,当您从testList 的循环中调用匿名函数时,它会重新运行与item 和i 变量保持完全相同的值。还要在循环中创建匿名函数,这不是最佳做法,我建议您像这样修改buildList 函数:

    function buildList(list) {
        var index = 0;
    
        return function () {
            if (index >= list.length) return
            var item = "item: " + list[index] + " i's value: " + index;
            document.body.innerHTML += [
              item, ", list[i]:", list[index], 
              ", i's value in the anonymous function:",
              index, "<br>"
            ].join('')
            index++
        }
    }
    
    function testList() {
        var list = [1, 2, 3];
        var testTheList = buildList(list);
        document.body.innerHTML = '';
        for (var j = 0; j < list.length; j++) {
            testTheList();
        }
    }
    
    testList();

    【讨论】:

    • 啊啊啊!谢谢我终于得到了一个有项目和我的。已经知道其他点,但不知何故被覆盖“项目”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2012-11-27
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多