+ 3
JS Palindromes function
Whats the mistake in my code? why it's not checking palindromes it's only return trur. function palindromes(str){ for(var i=str.length-1; i>=0; i--){ } for(var e=0; e<str.length; e++){ } if(str[i] === str[e]){ return true; } else{ return false; } }
7 Respostas
+ 19
+ 18
And, the error is that after the for loops, i becomes -1 and e becomes str.length and thus, str[i] and str[e] both are undefined. Thus, undefined === undefined. Thus, it always returns true.
+ 18
@Abdul Basit yes I'm Indian
@Code Learner I'm not 'sir'
+ 16
With the comma, we are using both the variables in a single loop. So, both the variables are used. One runs from str.length-1 to 0 and the vice versa for the other.
+ 2
@Abdul,@Swapnil
Swapnil sir's answer is correct. If two variables in for loop confuse you , you could do this way
function palindromes(str){
for(var i=0; i<str.length; i++){
if(str[i] != str[str.length-1-i]){
return false;
}
}
return true;
}
because you can find e by knowing i and vice versa.
+ 1
I didn't understand this for loop
for(var i=str.length-1, e=0; i>=0
&& e<str.length; i--,e++)
I mean the arrangement. Can we change the arrangement of variables?
+ 1
Ohhh... I didn't pay attention on comma. Cant we write both loop separately?
Are you Indian?