0
I would like to understand this code as simplistically as possible.
var palindromo = "";
for(var i = palavra.length - 1; i >= 0; i--) {
palindromo += palavra[i]
}
if (palavra == palindromo) {
return "SIM, SOU UM PALÍNDROMO"
} else {
return "INFELIZMENTE, NÃO SOU UM PALÍNDROMO"
}
I know that on the first go he does the reverse check.
But I want to understand the process of that part:
palindromo += palavra[i]
What the word EGG and the word YES would look like.
Seria:
Position of the word YES
0 = S 1 = I 2 = M
3 - 1 = heading 2 which is the letter’M'
palindromo += palavra[i]
"" = "" + YES [M] - Would that be it? How does this part?
This answers your question? Function to check palindrome
– Vagner Wentz
palavra[i]
picks up the character that is in positioni
stringpalavra
, then wheni
vale2
, the expressionpalavra[i]
results in a string containing only the letter "M". And as the operator+
, when applied to strings, does the concatenation, then the expressionpalindromo += palavra[i]
is adding the character at the end of the stringpalindromo
. Therefore, the loop adds the last letter, then the penultimate and so on, to the first. At the end the stringpalindromo
contains the characters ofpalavra
in reverse order, and if both are equal, it is because the string is a palindrome.– hkotsubo
I put as an answer what I thought.
– André
Actually, the index is not "M" or "I", and yes
2
or1
, etc. So wheni
vale2
, the expressionpalavra[i]
is "translated" aspalavra[2]
, which is the character that is in the position2
(i.e., the letter "M"). And in the third step, "MI" + "S" results in "MIS", not "SMI" (each new character is added at the end)– hkotsubo
But the idea is exactly what I put in the answer?
– André