什么时候是"var"?在js中需要吗? [英] When is "var" needed in js?

查看:50
本文介绍了什么时候是"var"?在js中需要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在JavaScript中使用var和不使用var之间的区别

有时候,我看到有人这样做

sometime, I saw people doing this

for(var i=0; i< array.length; i++){
 //bababa

}

但我也看到有人这样做...

but I also see people doing this...

for(i=0; i< array.length; i++){
 //bababa

}

两者之间有什么区别?谢谢你.

What is the different between two? Thank you.

推荐答案

永远不需要" var "关键字.但是,如果您不使用它,那么您声明的变量将在全局范围内公开(即作为 window 对象的属性).通常这不是您想要的.

The var keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object). Usually this is not what you want.

通常,您只希望变量在当前作用域中可见,这就是 var 为您执行的操作.它仅在当前作用域中声明变量(尽管请注意,在某些情况下,当前作用域"将与全局作用域"一致,在这种情况下,使用 var 与不使用之间没有区别) var ).

Usually you only want your variable to be visible in the current scope, and this is what var does for you. 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).

编写代码时,您应该喜欢以下语法:

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
}

这样做:

for(i=0; i< array.length; i++){
   //bababa
}

...将在全局范围内创建一个名为 i 的变量.如果有人碰巧也在使用全局 i 变量,那么您刚刚覆盖了他们的变量.

...will create a variable called i in the global scope. If someone else happened to also be using a global i variable, then you've just overwritten their variable.

这篇关于什么时候是"var"?在js中需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆