[removed] Forloop Difference between i++ and (i+1)

后端 未结 2 866
再見小時候
再見小時候 2020-12-12 05:36

I was building a javascript for loop and I want to compare the value of an array to the next value in the array.

If both values are not equal, I want to return true,

相关标签:
2条回答
  • 2020-12-12 06:04

    Quite simply, the indexes are the same in this expression:

    if(sortedLetters[i] !== sortedLetters[i++]) return true;
    

    If the for loop counter is at 3, for example, it will evaluate sortedLetters[3] !== sortedLetters[3] before incrementing the value.

    Using i++ in your for loop will also double-increment your counter.

    0 讨论(0)
  • 2020-12-12 06:13

    The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code:

    if(sortedLetters[i] !== sortedLetters[i++]) return true;
    

    does the same thing as:

    if(sortedLetters[i] !== sortedLetters[i]) return true;
    i = i + 1;
    

    As x !== x always is false for any stable value of x, the code does the same thing as:

    if(false) return true;
    i = i + 1;
    

    You can use the pre increment version ++i, but if you increment the variable in the statement, you shouldn't increment it in the loop also:

    for (i = 0; i < sortedLetters.length; ) {
      if (sortedLetters[i] !== sortedLetters[++i]) return true;
    }
    
    0 讨论(0)
提交回复
热议问题