Javascript for 循环索引变量成为全局范围的一部分?
也许我不知道 for
循环索引变量如何确定作用域,但当我的一个循环没有完成时,我感到非常惊讶,似乎是因为从循环内调用的函数包含一个 i
也是其 for
循环索引。
下面是我整理的一个小脚本来演示此行为:
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
循环的范围。
这是正确的吗?如果是这样,在 JavaScript 中定义 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');
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.
Is this correct? If so, what's a better practice for defining the index variable of a for
loop in javascript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Javascript 中,变量的作用域是
var
关键字。当使用var
声明变量时,变量的作用域为当前函数。当不使用var
关键字分配给变量时,假定您正在谈论相同或更高范围内已定义的变量。如果没有找到,则在最高范围内创建该变量。底线:使用
var
声明所有变量。In Javascript, variables are scoped with the
var
keyword. When declaring variables withvar
, the variable is scoped to the current function. When assigning to a variable without using thevar
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.Bottom line: declare all your variables using
var
.您应该使用
let
声明循环索引变量:这将为变量声明并设置正确的范围。
You should declare your loop index variable with
let
:That will declare and set the proper scope for the variable.
当您使用
var
声明变量时,您将它们的范围限定为当前执行上下文。如果不这样做,它们将成为全局对象(浏览器中的
window
)的属性。When you declare your variables with
var
, you scope them to the current execution context.When you don't, they become properties of the global object (
window
in a browser).