简体   繁体   中英

Why does my code output undefined before the reversed string?

I'm trying to reverse a string by looping through each of the words and inserting it into an empty string. The program then outputs undefinedolleh .

 function reverseString(str) { let final = ""; for (let i = str.length; i >= 0; i--) { final += str[i]; } return final; } console.log(reverseString("hello"));

Arrays and string indexing starts at 0. So you're trying to access the position at str.length which doesn't exist.

Start at str.length-1 :

 function reverseString(str) { let final = ""; for (let i = str.length-1; i >= 0; i--) { final += str[i]; } return final; } console.log(reverseString("hello"));

Your problem is that you are trying to access your string out of bounds. A string has an indice that goes from 0 to string.length - 1 .

By the way, there is alread an function that reverse an array. So, to reverse a string, you just need to transform it to array, reverse it, and tranform back to a string

 console.log("hello".split("").reverse().join(""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM