2012-11-06 80 views
0

这是我的代码:JavaScript函数在循环迭代器问题中循环?

function func(){ 
for(i=0; i < 5; i++){ 
    alert('g'); 
} 
} 

for(i=0; i < 5; i++){ 
    func(); 
    alert('h'); 
} 

我的预期是什么:gggghgggghgggghgggghggggh

但什么接到只是ggggh

我发现,是因为有功能范围,JS不会阻塞范围。我想知道的是如何保持这种行为。我的意思是强制类似块范围的东西。否则,制作真正令人讨厌的错误非常容易 - 例如同时使用别人写的功能或者你自己写的功能,但几个月前。

+5

不使用'var i'是你最大的错误。 –

+1

'var'不是可选的!分号不是可选的。 – epascarello

+1

@epascarello - 我不想开始另一个“分号大多是可选的”参数(虽然他们认为你错了!),但是我很好奇,如果OP代码中有一个点在你认为是分号的地方失踪? – nnnnnn

回答

3

这实际上并不需要处理函数与块范围 - 它与隐式全局变量有关。

短篇小说:你不小心在你for循环创建全球变量 - 如果你使用for(var i=0;而不是for(i=0;你会得到预期的结果。

稍长版本:与变量i的范围

alert("typeof i: " + typeof i); 
// Alerts "typeof i: undefined"  
function func() { 
    // References the *global* variable `i` 
    for(i=0; i < 5; i++){ 
    alert('g'); 
    } 
} 

// Creates a *global* variable `i` and sets it to 0 
for(i=0; i < 5; i++) { 
    alert("i at start of iteration: " + i); 
    // Alerts "i at start of iteration: 0" 
    func(); 
    // `func` has just altered *global* state - here's the proof 
    alert("i after call to func: " + i); 
    // Alerts "i at start of iteration: 5" 
    alert('h'); 
} 
alert("typeof i: " + typeof i); 
// Alerts "typeof i: number 
// `i` is now in the global scope. 

// Left as an exercise for the reader: 
// try it again with `var i=0;` in both of the `for` loops. 
2

问题。

function func(){ 
for(var i=0; i < 5; i++){ 
    alert('g'); 
} 
} 

for(var i=0; i < 5; i++){ 
    func(); 
    alert('h'); 
} 
0

尝试宣告i在你的函数的局部变量:

function func(){ 
    var i; 
    for(i=0; i < 5; i++){ 
    alert('g'); 
    } 
} 
0

在其他的答案已经说过,您的代码不工作,因为你不var声明i变量,这会自动使其成为全球。所以不是真正的功能与块范围问题。如果使用var来声明变量,那么变量的作用域将被限制在声明为的相同函数中,包括任何嵌套函数或全局函数(如果不在函数中)。

如果在嵌套函数中使用相同的变量名称,则内部作用域中的变量名称被称为“阴影”外部变量;在这种情况下,内部函数不能访问该名称的外部函数的变量,因为使用该名称只会给它自己的变量。可以这么说。虽然可以通过将全局变量视为window对象的属性来访问全局变量。

“我想知道的是如何保持这样的行为。我的意思是,迫使像块范围,否则很容易使真正讨厌的错误......”

嗯,不,一旦你正确地开始使用var,就不难避免这些错误。但是你可以通过引入立即调用匿名函数力块范围:

(function() { 
    // variables created in this function are accessible 
    // only within this function 
    var x, y, z; 
})(); 

console.log(typeof x); // "undefined" (x can't be seen from outside the function) 

各地function(){}括号是必需的,这样的功能被解释为表达而不是函数语句;最后多余的()是要立即执行该函数表达式。该结构的一个常见用途是将整个脚本包含在其中,以使其中的变量或函数不会变成全局变量,因此不会与其他JS包含文件中加载的其他脚本进行交互。 (您可以在块中声明的几个函数之间共享的块中具有伪全局变量)。

因此,例如,如果要将for语句的正文变为带有范围的“块”这个:

for (var i = 0; i < something; i++) { 
    (function() { 
     var x = i; 
     // do something with x 
    })(); 
}