Variable declaration necessary in for loop?

僤鯓⒐⒋嵵緔 提交于 2019-12-04 07:08:24

问题


What is the difference between:

  • for (var i=0; i<5; i++) {}
  • for (i=0; i<5; i++) {}

And is it necessary to include the var keyword?

I understand that the var keyword affects variable scope, but I'm having trouble understanding if it's necessary to include the keyword in for loops.


回答1:


In the second example, your variable is defined globally, so if you're in the browser environment, you can access it from the window object.

The first one is an equivalent of:

var i;
for (i=0; i<5; i++) {}

as all the variables in javascript are hoisted to the beginning of the scope.




回答2:


1

for (var i = 0; i < 5; ++i) {
  // do stuff
}

2

var i;
for (i = 0; i < 5; ++i) {
  // do stuff
}

3

for (i = 0; i < 5; ++i) {
  // do stuff
}

1 and 2 are the same.

3 you probably never mean to do — it puts i in the global scope.




回答3:


I am assuming your are using C#, Java or JavaScript. The short answer is you need the var if "i" has not already been declared. You do not need if it has already been declared.

For example:

var i;
for(i=1;i<=5;i++) {}

Now there may be some implicit variable typing depending on language and IDE, but relying on implicit typing can be difficult to maintain.

Hope this helps, good luck!



来源:https://stackoverflow.com/questions/28162901/variable-declaration-necessary-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!