Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...