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.

27th Sep 2017, 5:11 PM
Ifunanya
Ifunanya - avatar
4 Respostas
27th Sep 2017, 6:06 PM
Hatsy Rei
Hatsy Rei - avatar
+ 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 :)
27th Sep 2017, 6:08 PM
LynTon
LynTon - avatar
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);
29th Sep 2017, 10:12 AM
Ifunanya
Ifunanya - avatar
0
Thank you!
29th Sep 2017, 10:12 AM
Ifunanya
Ifunanya - avatar