Difference between pre-increment and post-increment in a loop?

后端 未结 22 1781
暗喜
暗喜 2020-11-21 23:41

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?

22条回答
  •  广开言路
    2020-11-22 00:24

    In javascript due to the following i++ may be better to use:

    var i=1;
    alert(i++); // before, 1. current, 1. after, 2.
    alert(i); // before, 2. current, 2. after, 2.
    alert(++i); // before, 2. current, 3 after, 3.
    

    While arrays (I think all) and some other functions and calls use 0 as a starting point you would have to set i to -1 to make the loop work with the array when using ++i.

    When using i++ the following value will use the increased value. You could say i++ is the way humans count, cause you can start with a 0.

提交回复
热议问题