Javascript for 循环索引变量成为全局范围的一部分? [英] Javascript for loop index variables become part of global scope?
问题描述
也许我不知道 for
循环索引变量是如何设置范围的,但是当我的一个循环没有完成时我感到非常惊讶,这似乎是因为从循环中调用的函数包含一个 i
也用于它的 for
循环索引.
Perhaps I'm not aware of how for
loop index variables get scoped, but I was very surprised when one of my loops didn't complete, seemingly because a function called from within a loop contained an i
for its for
loop index as well.
这是我编写的一个小脚本来演示这种行为:
Here's a little script I put together to demonstrate this behavior:
var loopOne = function(test) {
for(i = 0; i < test.length; i++)
console.log(getMask(test));
};
var getMask = function(pass) {
var s = "";
for (i = 0; i < pass.length; i++) {
s = s + "*";
}
return s;
};
loopOne('hello');
如果我在 Chrome 中运行它并查看控制台日志,我应该看到 *****
五次.然而,我只看过一次.进一步检查后,如果我在 Chrome javascript 控制台中输入 i
,它将输出 6 (='hello'.length + 1
).这让我觉得 i
已经成为全局作用域的一部分,并不仅限于需要它的 for
循环的作用域.
If I run this in Chrome and look at the console log, I should see *****
five times. However, I only see it once. Upon further inspection, if I type i
in the Chrome javascript console, it will output 6 ( = 'hello'.length + 1
). This makes me think that i
has become a part of the global scope and is not limited to the scope of the for
loop for which it was needed.
这是正确的吗?如果是这样,在 javascript 中定义 for
循环的索引变量的更好做法是什么?
Is this correct? If so, what's a better practice for defining the index variable of a for
loop in javascript?
推荐答案
在 Javascript 中,变量的作用域是 var
关键字.当使用 var
声明变量时,变量的作用域是当前函数.在不使用 var
关键字的情况下分配给变量时,假定您正在讨论相同或更高范围内的已定义变量.如果未找到,则在最高范围内创建该变量.
In Javascript, variables are scoped with the var
keyword. When declaring variables with var
, the variable is scoped to the current function. When assigning to a variable without using the var
keyword, it is assumed you're talking about an already defined variable in the same or a higher scope. If none is found, the variable is created in the highest scope.
底线:使用 var
声明所有变量.
Bottom line: declare all your variables using var
.
这篇关于Javascript for 循环索引变量成为全局范围的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!