问题描述
如果两个值都不相等,那么这个数组的值就是数组中的下一个值。我想要返回true,否则我想返回false。
在下面的代码中,我传递字符串aba,将其拆分并排序为
i ++ 正在使用后增量,所以表达式 i ++ 的值是变量 i 增量前。这段代码:
if(sortedLetters [i]!== sortedLetters [i ++])return true;
做同样的事情:
if(sortedLetters [i]!== sortedLetters [i])return true;
i = i + 1;
至于 x!== x false对于任何 x 的稳定值,代码的作用与以下相同:
if(false)返回true;
i = i + 1;
您可以使用前增量版本 ++ i ,但是如果你在语句中增加变量,你不应该在循环中增加它:
for i = 0; i< sortedLetters.length;){
if(sortedLetters [i]!== sortedLetters [++ i])return true;
}
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;解决方案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; }
这篇关于Javascript:Forloop i ++和(i + 1)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!