我是 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
可见。
关于使用 IIFE 的 Javascript 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660044/