JavaScript 中的递归

什么是递归?

递归是一个调用自身的过程。递归函数是为了执行函数而调用自身的函数。递归函数的语法是:

从上图中我们可以看到,该recurse()函数在其内部被调用。

递归函数的工作原理

递归函数无限运行,因此需要一个条件才能突破。这个条件通常是一个 if 语句。如果条件不满足,则递归函数运行,但立即满足该条件,递归函数返回一个值并停止运行。

递归和迭代之间的区别

许多开发人员将递归与迭代混为一谈。虽然它们执行类似的操作(即它们用于重复过程),但它们的语法有些不同。

递归使用函数调用使语句在函数体中重复运行,而迭代使用for、while和do while循环来重复执行语句。

大多数可以使用迭代方法解决的问题也可以使用递归来解决。

示例 1:
在这个例子中,我们想从给定的数字倒数到零。

使用迭代:

function countDown(n){
  for (let i = n; i > 0; i--){
    console.log(i);
  }
  console.log("Hurray");
}

// running our function
countDown(5);

输出:

5
4
3
2
1
Hurray

使用递归:

function countDownRecursive(n){
  // first we create our breakout condition 
  if (n < 1){
    return console.log("Hurray");
  }
  console.log(n);
  countDownRecursive(n-1);
}

// running our function
countDownRecursive(5);

输出:

5
4
3
2
1
Hurray

解释:
迭代函数 在使用的​​迭代方法中,我们可以看到,一旦输入数字被传递,并且函数被运行,变量 i 被注销然后减少,直到它变为 1 并打印“Hurray”。

递归函数 在递归方法中,会发生这种情况

countDown(5) prints 5 and calls countDown(4)
countDown(4) prints 4 and calls countDown(3)
countDown(3) prints 5 and calls countDown(2)
countDown(2) prints 5 and calls countDown(1)
countDown(1) prints 1 and calls countDown(0) which is less than 0, and hence returns "Hurray".

示例 2:
在此示例中,我们要在某个范围内添加数字,从该数字到一。

使用迭代:

function sumRange(n){
  let total = 0;
  for(let i = n; i > 0; i--){
    total += i;
  }
  return total;
}

console.log(sumRange(5));

输出:

15

使用递归:

function sumRangeRecursive(n, total = 0){
  if(n <= 0){
    return total;
  }
  return sumRangeRecursive(n-1, total + n);
}

console.log(sumRangeRecursive(5));

输出:

15

解释:
迭代函数 运行函数时,首先初始化总变量,并在从给定输入到 1 的范围内添加 i 并减少 i 直到 i 小于零并返回总结果

递归函数 需要两个参数,范围的起点和设置为零的总参数。这是运行函数时发生的情况,

sumRangeRecursive(5, total = 0) calls sumRangeRecursive(4, total = 0 + 5)
sumRangeRecursive(4, total = 5) calls sumRangeRecursive(3, total = 4 + 5)
sumRangeRecursive(3, total = 9) calls sumRangeRecursive(2, total = 9 + 3)
sumRangeRecursive(2, total = 12) calls sumRangeRecursive(3, total = 12 + 2)
sumRangeRecursive(1, total = 14) calls sumRangeRecursive(3, total = 14 + 1)
returns 15

谢谢大家阅读❤。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值