什么是递归?
递归是一个调用自身的过程。递归函数是为了执行函数而调用自身的函数。递归函数的语法是:
从上图中我们可以看到,该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
谢谢大家阅读❤。