js實現翻轉一個字符串


  字符串作在程序中是非常常見的,因為程序中絕大部分的數據都可以當作字符串來處理。在這里介紹幾種翻轉字符串的方法。

(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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM