简体   繁体   中英

What's wrong with this incrementing in javascript?

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

}


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

}

These two constructs return the same result: 0,1,2,3,4. Why? What are the differences between them? Does it matter what increment i use in for loop?

If you put ++ in front of the variable you increment the value before returning it (in that statement), if you put it behind you return the value, then increment it afterwards. Since you are doing nothing with the value in the statement the result after said statement is the same.

Consider this:

var i = 0;
var a = ++i; // a is 1
var b = i++; // b is also 1, i is now 2.

The former is a pre-increment, the latter a post-increment.

The difference is nothing your example as you're not assigning the result to anything, but show themselves quite alot when assigning the result to another variable.

var i = 0;
alert(i); // alerts "0"

var j = i++;
alert(j); // alerts "0" but i = 1

var k = ++i; 
alert(k); // alerts "2" and i = 2

Live example: http://jsfiddle.net/ggUGX/

for a loop you dont see any difference, but the ++i increments and then returns the value wheras i++ returns a value and then increments. If you have code like

var a = myarray[++i]

and

var a = mayarray[i++];

they will return differnet values

These two code blocks should have the same output. The difference between i++ and ++i is the order in which the variable i is incremented and is only important when using the value of i at the same time.

For instance, ++i and i++ do effectively the same thing unless you're using it like so:

y = i++;

or

y = ++i;

In the first example i is incremented AFTER y is set to its value (so if i = 0, y = 0, then i = 1). In the second example i is incremented BEFORE y is set to its value (so if i = 0, i = 1, y = 1).

Because you do not use i++ in a similar fashion in a for statement, it has no effective difference.

i++ or ++i in the for loop executes as a different statements. So, putting i++ or ++i in for loop doesn't make any difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM