0
How do i reverse a string in Javascript with for loops?
Could you please help with detailed explanation. Or if you could guide me step by step. I do not just get it.
4 Respostas
+ 11
+ 11
var word = "supercalifragilisticexpialidocious";
var newWord = "";
for (let i = word.length - 1; i >= 0; i--) {
newWord += word[i];
}
document.write(newWord);
First the string word and empty string newWord is created.
"i = word.length - 1" is 33 as the string word contains 34 characters.
Since this is 0-index based the first character has index 9 and final character has index 33, so newWord += word[33] makes newWord = "s", newWord += word[32] makes newWord = "su",
newWord += word[31] makes newWord = "suo",
etc....
and finally the loop goes through the letter's in the string breaks when i = -1, and the reversed original word is written.
Edit: Yep, that is what I mean't, happy to help :)
0
Thank you very much. You broke everything down for me. You meant that the first character has index 0, yes?
This is my code:
var word = "Elon Musk";
var newWord = "";
for (i = word.length - 1; i >= 0; i--) {
newWord += word[i];
}
document.write(newWord);
0
Thank you!