循环内的javascript var声明 [英] javascript var declaration within loop
问题描述
/*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",但超时后它输出测试 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);
}
当你的超时函数执行时,循环很长时间结束,no
保留其最终值 2.
By the time your timeout function executes, the loop is long finished, with no
retaining its final value of 2.
解决这个问题的一种方法是将 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声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!