javascript中的递归字符串反转函数? [英] Recursive string reversal function in javascript?
问题描述
我是一名经验丰富的前端工程师,但 CS 背景较弱.我试图让我的头脑围绕递归的概念.我能找到的大多数示例和声称的解释都没有以我认为易于理解的方式进行解释.
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?
推荐答案
类似:
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.
这篇关于javascript中的递归字符串反转函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!