Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - js什么时候需要“ var”? [重复](When is “var” needed in js? [duplicate])

Possible Duplicate:(可能重复:)

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.(谢谢。)   ask by Tattat translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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变量,那么您刚刚覆盖了他们的变量。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...