字符串作在程序中是非常常見的,因為程序中絕大部分的數據都可以當作字符串來處理。在這里介紹幾種翻轉字符串的方法。
(1)使用字符串函數
//使用數組翻轉函數 function reverseString(str){ var array = str.split(''); //轉換成字符串數組 array = array.reverse(); str = array.join(''); return str; } //簡寫 function reverseString1(str){ return str.split('').reverse().join(''); } console.log(reverseString("helloworld")); //dlrowolleh console.log(reverseString1("helloworld")); //dlrowolleh
(2)使用for循環
//使用for循環 function reverseString2(str){ var newStr = ""; for(var i=str.length-1; i>=0; i--){ newStr += str[i]; } return newStr; } console.log(reverseString2("helloworld")); //dlrowolleh
(3)使用遞歸
//使用遞歸 function reverseString3(str){ if(str===""){ return ""; }else{ return reverseString3(str.substr(1)) + str.charAt(0); } } console.log(reverseString3("helloworld")); //dlrowolleh //簡寫 function reverseString4(str) { return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0); } console.log(reverseString4("helloworld")); //dlrowolleh