问题是这样的:
“您的一位同事编写了以下代码例程,但是它无法按照她的预期方式工作。您能解释为什么吗?您将如何修复代码,以便提供同事所期望的输出?”
var output = [];
for (var i = 0; i < 5; i++) {
output[i] = function () {
console.log(i);
}
}
output[0](); // logs 5, not the expected 0
output[1](); // logs 5, not the expected 1
output[2](); // logs 5, not the expected 2
output[3](); // logs 5, not the expected 3
output[4](); // logs 5, not the expected 4
在本章中,我发现了先前示例中的一个错误,该错误很容易被发现。因此,分析运动让我感到担忧。
我了解闭包是可以访问父变量的函数。我不是想为我解决这个问题,而是想知道社区是否为我指出了解决此问题的正确方向。
我已经完成了关于此主题的研究,并且完成了另外2个关于闭包的教程,但我只是不理解这个问题。
谢谢
最佳答案
用var
声明的变量的范围是其当前的执行上下文,它可以是封闭函数,或者对于在任何函数之外声明的变量,是全局函数。 ->
Read more here
因此,基本上,每次执行都会使用最后分配给i
的值。
你有两个选择
1. IIFE
var output = [];
for (var i = 0; i < 5; i++) {
output[i] = (function(i) {
return function() {
console.log(i);
}
})(i);
}
output[0](); // logs 5, not the expected 0
output[1](); // logs 5, not the expected 1
output[2](); // logs 5, not the expected 2
output[3](); // logs 5, not the expected 3
output[4](); // logs 5, not the expected 4
2. Statement
let
let
语句声明一个块作用域局部变量,可以选择将其初始化为一个值。var output = [];
for (let i = 0; i < 5; i++) {
output[i] = function() {
console.log(i);
}
}
output[0](); // logs 5, not the expected 0
output[1](); // logs 5, not the expected 1
output[2](); // logs 5, not the expected 2
output[3](); // logs 5, not the expected 3
output[4](); // logs 5, not the expected 4