Recursive string reversal function in javascript?

前端 未结 12 1648
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 08:48

I\'m a pretty experienced frontend engineer with a weak CS background. I\'m trying to get my head around the concept of recursion. Most of the examples and purported explana

12条回答
  •  甜味超标
    2020-12-03 09:30

    It is verbose, but I like making it easy to understand in logical steps:

    function rev(soFar, count){
       console.log("asString: " + soFar );
       console.log("count: " + count);
       var len = soFar.length;
       var ret = soFar;//ret needs to be a reference to soFar
       if(len > count){
          var subd = soFar.substring(1,len);
          var first = soFar[0];
          //we want to inject the first letter at the index position one back from the length, minus what the count is at this point
          var indexOfInsert = len-1 - count;//so if count is 0 and length is 5, we want 4 (4 -0)
          var asArray = subd.split("");
          asArray.splice(indexOfInsert,0,first);
          count++;//need to increment count for the next round
          var asString = "";
        //recreate as string, not array - the default toString() makes this a comma delimited string. It is best toi just recreate it in a loop
        for(var i = 0; i

    }

    Then call it like:

    var reversed = rev("Hello",0);
    console.log("result",reversed);
    

提交回复
热议问题