Javascript - How does “++i” work?

▼魔方 西西 提交于 2019-12-06 11:14:19

问题


After experimenting with the use of "i++" and "++i" I could not find a difference between their results when used in a 'for' loop. For example:

for (var i = 0; i < 10; ++i) {
    console.log(i);
}

would yield:

0
1
2
3
4
5
6
7
8
9

Shouldn't it be printing out the numbers from 1 to 10, as the iterator is being incremented before console.log(i) executes?


回答1:


The "increment step" is executed after the loop body is executed. Given

for (a;b;c) {
  d
}

the execution order is

a // initialize
b // condition - first iteration
d // loop body
c // "increment"
b // condition - second iteration
d // loop body
c // "increment"
...
b // condition - last iteration - break

So in your case:

var i = 0;
i < 10;
console.log(i); // 0
++i;
i < 10;
console.log(i); // 1
++i;
// ...
i < 10;

The difference between i++ and ++i is only relevant if you do something with the return value, which you don't.




回答2:


Because the last clause of the for loop only happens at the end of the loop, as its own statement, the behavior of your loop is not affected by this difference. However, imagine you did something like this:

for (var i = 0; i < 10;) {
    console.log(++i);
}
for (var j = 0; j < 10;) {
    console.log(j++);
}

Then you'd see a difference. The first example would produce numbers 1-10, whereas the second would produce numbers 0-9. That's because f(j++) is equivalent to j += 1; f(j);, whereas f(++i) is more like f(i); i += 1;.




回答3:


May I advise that while your testing is fine on whatever platform you are using, the standard construct is i++

Always code the standard and isolate various platforms and make exceptions as needed !!!

i++ Simply means increment 'i' by one.

I can speculate ++i means to add 'i' to itself eg if 'i' was 2 then it would then increment to 2,4,8,16,32

But I have never seen ++i used in many places.



来源:https://stackoverflow.com/questions/25318554/javascript-how-does-i-work

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