Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

loops - Javascript: Forloop Difference between i++ and (i+1)

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, otherwise I want to return false.

In the code below I pass the string "aba", split it and sort it to

sortedLetters = ["a", "a", "b"]

Yet, when I compare sortedLetters[0] ("a") with sortedLetters[1]

function isIsogram(str){

    // split each letter into an array and sort
    sortedLetters = str.split("").sort();

    console.log(sortedLetters[0]); // is "a"
    console.log(sortedLetters[1]); // should be "a"

    // iterate through the array and see if the next array is equal to the current
    // if unequal, return true
    for( i = 0; i < sortedLetters.length; i++ ) {
        if(sortedLetters[i] !== sortedLetters[(i+1)]) return true;
    }
    // for "a" and "a", it should return false

    return false;

};

document.write(isIsogram("aba"));

Yet, why does the following if statement work, but the above code does not?

if(sortedLetters[i] !== sortedLetters[i++]) return true;
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...