递归javascript

by Kevin Ennis

凯文·恩尼斯(Kevin Ennis)

JavaScript中的递归 (Recursion in JavaScript)

I’m just gonna get this out of the way right up front, because people get really angry otherwise:

我只是直接解决这个问题,因为否则人们会非常生气:

Consider this post as a series of learning exercises. These examples are designed to make you think — and, if I’m doing it right, maybe expand your understanding of functional programming a little bit.

将此帖子视为一系列学习练习。 这些示例旨在让您思考-如果我做对的话,也许可以使您对函数式编程的理解有所扩展。

嘿,哇 我听说您喜欢递归,所以我说了“嘿,天哪。 我听说您喜欢递归,所以我说了“嘿,天哪…… (Hey, dawg. I heard you like recursion, so I put a “Hey, dawg. I heard you like recursion, so I put a “Hey, dawg…)

Loosely defined, recursion is the process of taking a big problem and sub-dividing it into multiple, smaller instances of the same problem.

松散地定义,递归是处理一个大问题并将其细分为相同问题的多个较小实例的过程。

Put into practice, that generally means writing a function that calls itself. Probably the most classic example of this concept is the factorial function.

付诸实践,通常意味着编写一个调用自身的函数。 此概念的最经典示例可能是阶乘函数。

You may remember from math class that the factorial of a number n is the product of all positive integers less than or equal to n. In other words, the factorial of 5 is 5 x 4 x 3 x 2 x 1. The mathematical notation for this is 5!.

您可能从数学课上还记得数字n的阶乘是所有小于或等于n的正整数的乘积 换句话说,阶乘55 x 4 x 3 x 2 x 1 。 为此的数学符号为5!

Something interesting you might have noticed about that pattern: 5! is actually just 5 x 4!. And 4! is just 4 x 3!. So on and so forth until you get down to 1.

关于该模式,您可能已经注意到了一些有趣的事情: 5! 实际上只有5 x 4! 。 还有4! 只有4 x 3! 。 依此类推,直到您降至1为止。

Here’s how we’d write that in JavaScript:

这是我们用JavaScript编写的方式:

If this seems confusing, I’d encourage you to mentally walk through the code using the example of factorial( 3 ).

如果这看起来令人困惑,我建议您使用factorial(3)的示例在代码上仔细地学习

Here’s a bit of help, in case you need it:

如果需要的话,这里有一些帮助:

  1. factorial( 3 ) is 3 x factorial( 2 ).

    factorial(3)3 x factorial(2)

  2. factorial( 2 ) is 2 x factorial( 1 ).

    factorial(2)2 x factorial(1)

  3. factorial( 1 ) meets our if condition, so it’s just 1.

    factorial(1)满足我们的if条件,因此仅为1。

So what’s really happening here is that you’re winding up the call stack, getting down to 1, and then unwinding the stack. As you unwind the call stack, you multiply each result. 1 x 2 x 3 is 6, and that’s your return value.

因此,这里真正发生的事情是结束调用堆栈,降低到1 ,然后展开堆栈。 展开调用堆栈时,将每个结果相乘。 1 x 2 x 36 ,这就是您的返回值。

反转字符串 (Reversing A String)

One of my co-workers recently told me about a whiteboard question that he’d been asked in an interview, and I thought it was kind of a fun problem.

我的一位同事最近告诉我一个关于白板问题的采访中有人问他,我认为这是一个有趣的问题。

Write a function that accepts a string a reverses it. Recursively.

编写一个接受字符串并将其反转的函数。 递归地。

If you’re the ambitious type, I’d encourage you to take a few minutes and try to solve this one on your own. Keep in mind the core principle of recursion, which is to take a big problem and break it down into smaller instances of itself.

如果您是一个有野心的人,我建议您花几分钟时间,尝试自己解决这个问题。 请记住递归的核心原则,即解决一个大问题并将其分解为更小的实例。

If you got stuck (or you’re the decidedly unambitious type), here’s my solution:

如果你卡住了(或者你是决然不思进取型),这里是我的解决方案:

Again, I’ll give a quick walk-through example in case you got stuck. We’ll use reverse(‘bar’) as a starting point.

再次,我将给出一个快速的示例,以防您陷入困境。 我们将使用reverse('bar')作为起点。

  1. reverse(‘bar’) is reverse(‘ar’) + ‘b’

    reverse('bar')reverse('ar')+'b'

  2. reverse(‘ar’) is reverse(‘r’) + ‘a’

    reverse('ar')reverse('r')+'a'

  3. reverse(‘r’) meets our if condition, so it’s just ‘r’

    reverse('r')满足我们的if条件,所以它只是'r'

When the call stack unwinds, we end up with ‘r’ + ‘a’ + ‘b’.

当调用堆栈结束时,我们最终得到'r'+'a'+'b'

编写递归映射函数 (Writing a Recursive Map Function)

For our final example, we’re going to write a map() function. We want to be able to use it like this:

对于最后一个示例,我们将编写一个map()函数。 我们希望能够像这样使用它:

Again, I’d strongly encourage you to take a few minutes and try this one on your own. Here are a few hints and reminders:

再一次,我强烈建议您花几分钟时间,自己尝试一下。 以下是一些提示和提醒:

  1. map() should always return a new array.

    map()应该始终返回一个数组。

  2. Break the problem down into smaller chunks.将问题分解成小块。
  3. Remember the reverse() example.

    记住reverse()示例。

Oh, good. You’re back. How did it go?

哦好 你回来了。 怎么样了

j/k, this is a blog and I can’t hear you. lol.

j / k,这是一个博客,我听不到您的声音。 大声笑。

Anyway, here’s how I did it:

无论如何,这是我的做法:

So let’s go through this using the example I gave earlier:

因此,让我们使用我之前给出的示例来完成此操作:

  1. Call map() using the array [ ‘a’, ‘b’, ‘c’ ]

    使用数组['a','b','c']调用map()

  2. Create a new array that holds the result of calling fn(‘a’)

    创建一个数组,其中包含调用fn('a')的结果

  3. Return [ ‘A’ ].concat( map([ ‘b’, ‘c’ ]) )

    返回['A'] .concat(map(['b','c']))

  4. Repeat steps 1 through 3 with [ ‘b’, ‘c’ ]

    ['b','c']重复步骤1至3

  5. Repeat steps 1 through 3 for [ ‘c’ ]

    ['c']重复步骤1至3

  6. Eventually, we call map() with an empty array, which ends the recursion.

    最终,我们使用一个空数组调用map() ,从而结束了递归。

NOTE:You should never, ever, ever do this in a real application. You’ll blow out the stack on large arrays, and more importantly, you create a huge amount of garbage by instantiating so many new objects. Use Array#map in production code.

注意:您永远不要在真实的应用程序中这样做。 您将炸毁大型阵列上的堆栈,更重要的是,通过实例化许多新对象来创建大量垃圾。 在生产代码中使用Array#map

结语 (Wrap Up)

Hopefully I did a decent job in explaining this stuff. If you’re still struggling a bit to wrap your head around recursion, the best advice I can give is to start with small examples and mentally trace the call stack. Try something like reverse(‘abc’) and walk through it, step-by-step. Eventually it’ll click.

希望我在解释这些东西方面做得不错。 如果您仍在努力地绕过递归,那么我可以提供的最佳建议是从小的示例开始,并从心理上跟踪调用堆栈。 尝试类似reverse('abc')之类的步骤,并逐步进行操作。 最终它将单击。

— -

--

Follow me on Twitter or Medium for more posts. I’m trying to write once a day for the next 30 days.

在Twitter或Medium上关注我以获取更多帖子。 在接下来的30天里,我每天尝试写一次。

And if you’re in the Boston area and want to come work on crazy, interesting, hard problems with me at Starry, shoot me an email. I’m hiring.

如果您在波士顿地区,并且想在Starry与我一起解决疯狂,有趣,棘手的问题,请给我发送电子邮件 。 我在招聘。

翻译自: https://www.freecodecamp.org/news/recursion-in-javascript-1608032c7a1f/

递归javascript

递归javascript_JavaScript中的递归相关推荐

  1. java filefilter递归_Java中的递归+文件过滤器

    直接递归称为方法自身调用自己 间接递归可以A方法调用B方法,B方法调用方法,C方法调用A方法. 注意事项: 递归一定要有条件限定,保证递归能够停止下来,否则会发生栈内存溢出. 在递归中虽然有限定条件, ...

  2. Java解决递归栈溢出_方法递归调用中java栈溢出的问题 及 解答 | 学步园

    为什么运行如下程序 , 方法sum2 不会导致栈溢出, 方法sum 会导致栈溢出? --------output----------- 32004000 java.lang.StackOverflow ...

  3. java 建树源码_Java实现的二叉树常用操作【前序建树,前中后递归非递归遍历及层序遍历】...

    import java.util.ArrayDeque; import java.util.Queue; import java.util.Stack; //二叉树的建树,前中后 递归非递归遍历 层序 ...

  4. Sql中的递归问题-思考与建议

    Sql中的递归问题 [递归] 是一种循环方式或规则 树的遍历常常用到 优点:编写程序方便 缺点:限制与内存,容易崩溃 [描述] 类别表 CID,CName,FID FID=0表示此节点为根节点 如何在 ...

  5. 可能存在无限递归_做事永远无头无尾?人生中的递归现象

    不知道大家有没有发现,在自己身边的人或者说就是自己,无论在职场还是学习中,有时候会陷入一种瞎忙碌的状态, 在周围的人看来你很忙碌,但是一旦需要拿出成果的时候,却又显得不尽人意,而最近的我就陷入了这样一 ...

  6. vue树形结构html,怎么在vue中利用递归组件实现一个树形控件

    怎么在vue中利用递归组件实现一个树形控件 发布时间:2021-06-11 17:26:48 来源:亿速云 阅读:81 作者:Leah 本篇文章为大家展示了怎么在vue中利用递归组件实现一个树形控件, ...

  7. 算法练习day10——190328(二叉树的先序、 中序、 后序遍历, 包括递归方式和非递归方式、找到一个节点的后继节点、二叉树的序列化和反序列化)

    1.实现二叉树的先序. 中序. 后序遍历, 包括递归方式和非递归方式 1.1 访问节点的顺序 节点访问顺序如下图所示: 访问顺序:1 2 4 4 4 2 5 5 5 2 1 3 6 6 6 3 7 7 ...

  8. 递归函数python有什么特点_Python中的递归

    在前面的讲解中,函数的调用通常发生在彼此不同的函数之间.其实,函数还有一种特殊的调用方式,那就是自己调用自己,这种方式称为函数递归调用. 递归,在程序设计中也是一个常用的技巧,甚至是一种思维方式,非常 ...

  9. 二叉树的层序遍历,前序遍历(递归,非递归),中序遍历(递归,非递归),后续遍历(递归,非递归)

    文章目录 二叉树的层序遍历 前序遍历 递归版本 非递归版本 中序遍历 递归版本 非递归版本 后序遍历 递归版本 非递归版本 二叉树的层序遍历 void printTree(BinaryTree* ar ...

最新文章

  1. 【SSM】Kisso实用教程(二)
  2. 邀您共赴数据库学术顶会ICDE 2019——阿里云专场 零距离接触达摩院数据库“最强大脑”...
  3. 为什么要在定义抽象类时使用abstract关键字
  4. Apache Nifi 实战:多表导入实现及填坑 GitChat连接
  5. java实现键盘移动图片,快速移动视图与键盘
  6. Java设计模式之Adapter模式
  7. 程序员记录之人性弱点
  8. Unity一键更换TextMeshPro的字体
  9. Android跳转到应用商店详情页面
  10. word格式文档在linux打开吗,ubuntu 打开word文档 ubuntu word 文档
  11. Python实验报告
  12. 昆石VOS3000/VOS2009 2.1.6.00 操作指南相关
  13. 影响蓝牙耳机音质的是什么因素?拒绝踩雷,这五款蓝牙耳机赶紧收藏
  14. 微信撤回软件安卓版_微信拍一拍撤回软件下载
  15. 逆势增长背后的启示:亚信科技公布2022中期业绩
  16. BZOJ3032 七夕祭 均分纸牌问题的变式 (前缀和+中位数)
  17. redis中键值出现 \xAC\xED\x00\x05t\x00\x11的原因和解决方法
  18. 伪原创视频 审核 原创视频md5
  19. shell 脚本实现 k8s 集群环境下指定 ns 资源的 yaml 文件备份
  20. 安装及使用pixsfm记录

热门文章

  1. Qt的安装和使用中的常见问题(详细版)
  2. UML 中extend和include的区别
  3. 01-hibernate注解:类级别注解,@Entity,@Table,@Embeddable
  4. webstorm环境安装配置(less+autoprefixer)
  5. Java BigDecimal Rounding Mode
  6. BZOJ1054(搜索)
  7. 四色原型图进行业务建模的思考
  8. [导入]ASP.NET MVC框架开发系列课程(1):MVC模式与ASP.NET MVC框架概述.zip(8.80 MB)
  9. Unity3D 自动打包整个项目(以AssetBundle实现)
  10. 3.Contructor(构造器)模式—精读《JavaScript 设计模式》Addy Osmani著