JavaScript中的递归字符串反转函数?
我是一位经验丰富的前端工程师,计算机科学背景较弱。我正在尝试理解递归的概念。我能找到的大多数例子和所谓的解释都没有以我认为容易理解的方式解释。
我给自己设定了一个任务,编写一个函数来递归地反转字符串。我知道必须有一个基本条件(即找到解决方案),但我不知道如何实际编写这样的东西,并且可以使用演示来研究。
有人可以提供示例功能吗?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
类似于:
所以该函数是递归的,因为它调用自身来完成工作。
Something like:
So the function is recursive as it calls itself to do the work.
尾递归版本,只是为了好玩(即使 JavaScript 不执行尾调用消除):
A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):
使用布尔运算符的一行代码。
说明:如果字符串存在,则调用递归来减少字符串,否则回退到不存在的字符串(最后一次递归调用)
One line of code using boolean operators.
Explanation: if string exists call the recursion to reduce the string, otherwise fallback to non existing string (last recursive call)
速度提高 25% 的函数:jsperf.com
A 25% faster function: jsperf.com
//以字符串作为参数调用该函数
//call this function with the string as parameter
根据 MDN Web 文档 ,您应该使用
substring()
而不是substr()
:此外,如果没有提供索引作为
charAt()
,默认为0
。因此,我们可以编写一个递归单行代码来使用 三元运算符 并应用上述逻辑:
According to the MDN Web Docs, you should use
substring()
instead ofsubstr()
:Additionally, if no index is provided as a parameter to
charAt()
, the default is0
.Therefore, we can write a recursive one-liner to reverse a string using a ternary operator and by applying the logic described above:
我用于退出递归的基本情况是当长度减少到 0 时
在每个递归调用中我们将取出字符串的最后一个字符并将其附加到我们从字符串的递归调用中获得的结果,由于使用切片删除了最后一个字符,因此其尺寸较小。
The base case that I am using for exiting the recursion is when the the length decrease to 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.
您还可以使用下面的代码通过递归简单反转字符串
You can also use this code below for simple reversal of strings through recursion
我是这样解决的:
Here is how I solved it:
另一个解决方案:
Another solution:
另一种使用默认参数的解决方案:
Another solution using default parameters:
到目前为止我认为最好的:
So far the best I think:
试试这个:
Try this:
它很冗长,但我喜欢以逻辑步骤使其易于理解:
}
然后这样称呼它:
It is verbose, but I like making it easy to understand in logical steps:
}
Then call it like:
这是您所要求的算法的非常简单的 C# 实现。
我认为它可以很容易地用 JavaScript 重写。
This is a pretty straightforward C# implementation of the algorithm you asked for.
I think it could be rewritten in javascript pretty easily.