Javascript IIFE 的变量作用域
Javascript variable scoping with IIFE
我是 Javascript 的新手,正在尝试使用 setTimeout
在 for 循环中遍历数组,这是代码的一部分,所以默认情况下我有 100 毫秒。
我期望输出为 1、2、3,但它的所有打印都是未定义的 3 次。
如果有人能帮我解释为什么会有帮助。
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(temp){
console.log(allCars[temp]);
},100)})(i);
}
setTimeout
不会将任何参数(除非您指定一个)传递给它的回调,但您指定了一个名为 temp
的参数,它隐藏了外部的 temp
范围。
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(temp){ // This temp hides the temp on the line above
console.log(allCars[temp]);
},100)})(i);
}
只需从传递给 setTimeout
的回调中删除参数,即可让外部 temp
可见。
这是应该产生正确结果的更新代码。将参数传递给 setTimeout
时遇到的问题
这是更新的代码
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(){
console.log(allCars[temp]);
},100)})(i);
}
我是 Javascript 的新手,正在尝试使用 setTimeout
在 for 循环中遍历数组,这是代码的一部分,所以默认情况下我有 100 毫秒。
我期望输出为 1、2、3,但它的所有打印都是未定义的 3 次。
如果有人能帮我解释为什么会有帮助。
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(temp){
console.log(allCars[temp]);
},100)})(i);
}
setTimeout
不会将任何参数(除非您指定一个)传递给它的回调,但您指定了一个名为 temp
的参数,它隐藏了外部的 temp
范围。
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(temp){ // This temp hides the temp on the line above
console.log(allCars[temp]);
},100)})(i);
}
只需从传递给 setTimeout
的回调中删除参数,即可让外部 temp
可见。
这是应该产生正确结果的更新代码。将参数传递给 setTimeout
时遇到的问题
这是更新的代码
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(){
console.log(allCars[temp]);
},100)})(i);
}