/*Test scope problem*/
for(var i=1; i<3; i++){
//declare variables
var no = i;
//verify no
alert('setting '+no);
//timeout to recheck
setTimeout(function(){
alert('test '+no);
}, 500);
}
Run Code Online (Sandbox Code Playgroud)
它按预期警告"设置1"和"设置2",但在超时后它输出"测试2"两次 - 由于某种原因,变量"否"在第一次循环后没有重置......
我发现只有一个"丑陋"的解决方法:
/*Test scope problem*/
var func=function(no){
//verify no
alert('setting '+no);
//timeout to recheck
setTimeout(function(){
alert('test '+no);
}, 500);
}
for(var i=1; i<3; i++){
func(i);
}
Run Code Online (Sandbox Code Playgroud)
有关如何以更直接的方式解决此问题的任何想法?或者这是唯一的方法吗?