问题描述
/*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);
}
它按预期警告设置1和设置2,但之后超时它输出test 2两次 - 由于某种原因,变量no在第一次循环后没有重置...
It alerts "setting 1" and "setting 2" as expected, but after the timeout it outputs "test 2" twice - for some reason the variable "no" is not reset after the first loop...
我发现只有一个丑陋的解决方法:
I've found only an "ugly" workaround:
/*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);
}
有关如何以更直接的方式解决此问题的任何想法?或者这是唯一的方法吗?
Any ideas on how to workaround this problem in a more direct way? or is this the only way?
推荐答案
JavaScript没有块范围,并且提升了变量声明。这些事实共同意味着您的代码相当于:
JavaScript does not have block scope, and variable declarations are hoisted. These facts together mean that your code is equivalent to:
var no;
/*Test scope problem*/
for(var i=1; i<3; i++){
//declare variables
no = i;
//verify no
alert('setting '+no);
//timeout to recheck
setTimeout(function(){
alert('test '+no);
}, 500);
}
当你的超时功能执行时,循环结束很长时间,用否
保留其最终值为2。
By the time your timeout function executes, the loop is long finished, with no
retaining its final value of 2.
解决这个问题的方法是传递<$ c的当前值$ c> no 进入一个函数,为每次调用 setTimeout
创建一个新的回调。每次创建一个新函数意味着每个setTimeout回调都绑定到具有自己的变量集的不同执行上下文。
A way around this would be to pass the current value of no
into a function that creates a fresh callback for each call to setTimeout
. Creating a new function each time means each setTimeout callback is bound to a different execution context with its own set of variables.
var no;
/*Test scope problem*/
for(var i=1; i<3; i++){
//declare variables
no = i;
//verify no
alert('setting '+no);
//timeout to recheck
setTimeout( (function(num) {
return function() {
alert('test '+num);
};
})(no), 500);
}
这篇关于循环中的javascript var声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!