Reputation: 49
I personally cannot figure out why this function works the way it does. The value of variable "i" is per each iteration right? So wouldn't the "i" in the "str[str.length-i-1]" means to skip out one of the elements of the array made by split after subtracting from the length and then 1?
For example, of how I envision it, once the second iteration comes in, wouldn't it be: "racecar[7-2-1]" since i is 2? Then it would be racecar[4] right? However, racecar is a palindrome so it does return true; many challenge videos does not explain why the "i" is working as such. Any experienced help would be appreciated!
function palindrome2(str){
return str.split('').every((char, i)=> {
console.log(i)
return char === str[str.length-i-1]
});
}
console.log(palindrome2("racecar"))
Upvotes: 0
Views: 43
Reputation: 49
Oh I got it! I took it out step by step and now it makes more sense! The console log of "i" confused me even more.. So i just replaced everything I can after every iteration. Every letter matches each index it is iterating over! WOo hoo
function palindrome2(str){
return str.split('').every((r, 0)=> {
return r === racecar[7-0-1]
});
}function palindrome2(str){
return str.split('').every((a, 1)=> {
return a === racecar[7-1-1]
});
}
}function palindrome2(str){
return str.split('').every((c, 2)=> {
return c === racecar[7-2-1]
});
}
Upvotes: 1