gpt4 book ai didi

关于外部变量的 JavaScript 和闭包

转载 作者:行者123 更新时间:2023-11-30 16:40:33 25 4
gpt4 key购买 nike

<分区>

我一直在阅读一本关于 JavaScript 的书,作者用几页的篇幅谈到了闭包的主题。在一页上,他展示了以下示例:

function wrapElements(a) {
var result = [], i, n;
for (i = 0, n = a.length; i < n; i++) {
result[i] = function() { return a[i]; };
}
return result;
}

var wrapped = wrapElements([10, 20, 30, 40, 50]);
var f = wrapped[0];

现在,他说人们可能期望 f(); 返回 10,但它实际上返回 undefined

他是这样说的:

The bug in the program comes from the fact that the programmer apparently expected the function to store the value of i at the time the nested function was created. But in fact, it contains a reference to i. Since the value of i changes after each function is created, the inner functions end up seeing the final value of i. [...] Since each iteration of the loop increments i until it runs off the end of the array, by the time we actually call one of the closures, it looks up index 5 of the array and returns undefined.

但我就是无法理解他的解释。我再次阅读了他之前关于闭包的解释(并且认为我理解它们——但显然,我似乎不理解)并且我在 Internet 上搜索了更多关于闭包的信息。我还是不明白为什么 f(); 会返回 undefined

匿名函数不会在循环的每次迭代中被创建和调用吗?因此,它不会查找所有索引而不仅仅是索引 5 吗?还是我误解了什么?

谁能帮帮我?谢谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com