Is there a difference between ++i and i++ in this loop?

后端 未结 1 1381
不思量自难忘°
不思量自难忘° 2020-12-19 21:24

The array.prototype.reduce function at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

It has the following loop:

相关标签:
1条回答
  • 2020-12-19 21:47

    The only difference between i++, ++i, and i += 1 is the value that's returned from the expression. Consider the following:

    // Case 1:
    var i = 0, r = i++;
    console.log(i, r); // 1, 0
    
    // Case 2:
    var i = 0, r = ++i;
    console.log(i, r); // 1, 1
    
    // Case 3:
    var i = 0, r = (i += 1);
    console.log(i, r); // 1, 1
    

    In these cases, i remains the same after the increment, but r is different, i += 1 just being a slightly more verbose form of ++i.

    In your code, you're not using the return value at all, so no, there is no difference. Personally, I prefer to use i++ unless there is a specific need to use one of the other forms.

    0 讨论(0)
提交回复
热议问题