javascript javascript中的递归字符串反转函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4859208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:08:06  来源:igfitidea点击:

Recursive string reversal function in javascript?

javascriptrecursion

提问by Geuis

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 explanations I can find just aren't explaining it in a way I find easy to understand.

我是一名非常有经验的前端工程师,具有较弱的 CS 背景。我试图让我的头脑围绕递归的概念。我能找到的大多数示例和声称的解释都没有以我认为易于理解的方式进行解释。

I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.

我给自己设定了一个任务,即编写一个递归反转字符串的函数。我知道必须有一个基本条件(即找到解决方案),但我无法弄清楚如何实际编写这样的东西,可以使用演示来研究。

Could someone provide a sample function?

有人可以提供示例功能吗?

回答by Tom

Something like:

就像是:

function reverse (str) {
    if (str === "") {
        return "";
    } else {
        return reverse(str.substr(1)) + str.charAt(0);
    }
}

So the function is recursive as it calls itself to do the work.

因此该函数是递归的,因为它调用自己来完成工作。

回答by maerics

A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):

尾递归版本,仅用于踢球(即使 JavaScript 不执行尾调用消除):

function reverse(str) {
  function r(s, acc) {
    return (s.length == 0) ? acc : r(s.substr(1), s.charAt(0) + acc);
  };
  return r(str, '');
};

回答by Eugen Sunic

One line of code using ternary operatorsyou can easily reverse it.

一行代码使用三元运算符就可以轻松反转它。

Explanation: if string exists (if not null) then return recursion otherwise stop the recursion.

说明:如果字符串存在(如果不为空)则返回递归,否则停止递归。

  function reverseString(str) {
    return (str ? reverseString(str.substring(1)) + str.charAt(0) : str);
  }

Function call:

函数调用:

console.log(reverseString('hello'));

回答by Dima Daron

A 25% faster function: jsperf.com

速度提高 25% 的功能:jsperf.com

function Reverse(str) {
  if (str === null) {
    return null;
  }
  if (str.length <= 1) {
    return str;
  }
  var first = str[0];
  var last = str[str.length - 1];
  var str1 = Reverse(str.substring(1, str.length - 1));
  return last + str1 + first;
}

var result = Reverse("a really serious string of nothingness making call stack to explode");

回答by Rahul kishan

function reverse(str) {
  if(str.charAt(0) === ''){
    return "";
  }
  return str.charAt(str.length -1) + reverse(str.substring(0,str.length-1));
}

回答by shantanu kaushik

//call this function with the string as parameter

//以字符串为参数调用此函数

function strrev(str) {
    return str.length !== 1 ? strrev(str.slice(1))+str[0] : str;
}

回答by Grant Miller

According to the MDN Web Docs, you should use substring()instead of substr():

根据MDN Web Docs,您应该使用substring()代替substr()

Warning: Although String.prototype.substr(…)is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy functionand should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring()method instead.

警告:虽然String.prototype.substr(…)并未严格弃用(如“从 Web 标准中删除”),但它被视为遗留功能,应尽可能避免使用。它不是核心 JavaScript 语言的一部分,将来可能会被删除。如果可能,请改用该substring()方法。

Additionally, if no index is provided as a parameter to charAt(), the default is 0.

此外,如果没有提供索引作为 的参数charAt(),则默认为0

Therefore, we can write a recursive one-liner to reverse a string using a ternary operatorand by applying the logic described above:

因此,我们可以使用三元运算符并应用上述逻辑编写一个递归单行来反转字符串:

const reverse_string = s => s === '' ? '' : reverse_string(s.substring(1)) + s.charAt();

console.log(reverse_string('Hello, world!')); // !dlrow ,olleH

回答by HarsimranJS

The base case that I am using for exiting the recursion is when the the length decrease to 0

我用于退出递归的基本情况是长度减少到 0

On each recursive call we will take out the last character of the string and append it with the result that we will get from recursive call of a string, which is smaller in size as the last character is removed using slice.

在每次递归调用中,我们将取出字符串的最后一个字符并将其附加到我们将从字符串的递归调用中获得的结果,由于使用切片删除了最后一个字符,因此字符串的大小更小。

function reverse(str){
 if(str.length===0)
    return "";

return str[str.length-1]+reverse(str.slice(0,str.length-1));
}

回答by Gerrat

Try this:

试试这个:

function recurse(s) {  
  if (s.length == 0) {  
    return '' // stopping condition  
  } else {  // return last char + result of function called with chars up to last char  
    return s.substring(s.length, s.length -1) + recurse(s.substring(0, s.length -1))  
  }
}  

回答by qweszxcj

So far the best I think:

到目前为止,我认为最好的:

function reverse(s) {
    if (s.length===1) return s;
    return reverse(s.slice(1)) + s[0];
}