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

你。 提交于 2019-11-30 09:03:47

问题


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:

for (index = 0; length > index; ++index) {
    if (this.hasOwnProperty(index)) {
      if (isValueSet) {
         value = callback(value, this[index], index, this);
      } else {
        value = this[index];
        isValueSet = true;
      }
    }
}

I don't think there is a difference whether the index is pre or post incremented here since it's done after the loop iterates each time, but want to be certain.

Can this be changed to index += 1 so it passes jslint? Please don't debate the merits of jslint's warning.

Would this change make any difference?


回答1:


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.



来源:https://stackoverflow.com/questions/22084653/is-there-a-difference-between-i-and-i-in-this-loop

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