The var
keyword is never "needed".(绝对不需要“ var
关键字。)
However if you don't use it then the variable that you are declaring will be exposed in the global scope (ie as a property on the window
object).(但是,如果您不使用它,那么您声明的变量将在全局范围内公开(即,作为window
对象的属性)。) Usually this is not what you want.(通常这不是您想要的。)
Usually you only want your variable to be visible in the current scope, and this is what var
does for you.(通常,您只希望变量在当前作用域中可见,这就是var
为您所做的。) It declares the variable in the current scope only (though note that in some cases the "current scope" will coincide with the "global scope", in which case there is no difference between using var
and not using var
).(它仅在当前作用域中声明变量(尽管请注意,在某些情况下,“当前作用域”将与“全局作用域”一致,在这种情况下,使用var
和不使用var
之间没有区别)。)
When writing code, you should prefer this syntax:(在编写代码时,您应该喜欢以下语法:)
for(var i=0; i< array.length; i++){
//bababa
}
Or if you must, then like this:(或者,如果必须,则如下所示:)
var i;
for(i=0; i< array.length; i++){
//bababa
}
Doing it like this:(这样做:)
for(i=0; i< array.length; i++){
//bababa
}
...will create a variable called i
in the global scope.(...将在全局范围内创建一个名为i
的变量。) If someone else happened to also be using a global i
variable, then you've just overwritten their variable.(如果其他人碰巧也在使用全局i
变量,那么您刚刚覆盖了他们的变量。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…