How do you reverse a string in place in JavaScript?

前端 未结 30 2390
猫巷女王i
猫巷女王i 2020-11-22 00:29

How do you reverse a string in place (or in-place) in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse()<

30条回答
  •  长发绾君心
    2020-11-22 00:44

    My own original attempt...

    var str = "The Car";
    
    function reverseStr(str) {
      var reversed = "";
      var len = str.length;
      for (var i = 1; i < (len + 1); i++) {  
        reversed += str[len - i];      
      }
    
      return reversed;
    }
    
    var strReverse = reverseStr(str);    
    console.log(strReverse);
    // "raC ehT"
    

    http://jsbin.com/bujiwo/19/edit?js,console,output

提交回复
热议问题