Variable declaration necessary in for loop?

2019-03-07 03:28发布

问题:

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!