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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…