如何理解JavaScript中的递归
什么是递归
递归一词来源于”重复出现”,意思是一次又一次地回到原来的地方。递归函数是指通过逐步改变输入自己再次调用自己的函数。在这里,逐步改变输入意味着逐步减少或增加输入。
每当递归函数达到基本条件时,它将停止执行自己。让我们通过一个示例来理解什么是基本条件。例如,我们需要找出一个数的阶乘。我们通过将输入减1来调用阶乘函数,并且当输入达到1时,我们需要停止。因此,其中的1作为基本条件。
语法
用户可以使用以下语法来理解JavaScript中的递归。
function recur(val) {
if (base condition) {
return;
}
// perform some action
// decrease the value of val by one step
return recur(newVal);
}
在上面的语法中,用户可以观察到当基本条件为真时,我们返回null来停止函数的执行。如果基本条件为假,我们会对输入值执行某些操作,并再次使用新的参数值调用recur()函数。
现在,让我们看一下递归的各种示例。在这里,我们将首先通过使用for循环来实现迭代算法,然后将其转换为递归方法。
示例1(使用for循环找到1到n个数字的和)
在下面的示例中,我们编写了sumOfN()函数来获取1到N个数字的总和。我们使用for循环进行N次迭代,每次迭代都将I的值添加到sum变量中。
最后,它返回sum变量的值。
<html>
<body>
<h3>Using the <i> iterative approach </i> to find sum of n numbers in JavaScript</h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// function to find the sum of n numbers using an iterative approach
function sumOfN(n) {
let sum = 0;
for (let i = n; i >= 1; i--) {
sum += i;
}
return sum;
}
content.innerHTML += "The sum of 1 to 10 numbers is " + sumOfN(10) + "<br>";
content.innerHTML += "The sum of 1 to 20 numbers is " + sumOfN(20) + "<br>";
</script>
</body>
</html>
在上面的示例中,我们使用了迭代的方法来找到N个数的和。现在,我们将使用递归的方法来做同样的事情。
示例2(使用递归函数求1到n个数的和)
sumOfN()函数是下面示例中的递归函数。我们通过将参数的值减1来反复调用sumOfN()函数。sumOfN(N1)返回N-1个数的和,我们将N添加到它上面得到N个数的和。当N的值变为1时,它返回一个值,这个值作为停止执行函数的基本条件。
<html>
<body>
<h3>Using the <i> recursive approach </i> to find sum of n numbers in JavaScript</h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// function to find the sum of n numbers using a recursive approach
function sumOfN(n) {
// base condition
if (n == 1) {
return 1;
}
// call function recursively by decreasing the value of n by 1.
return n + sumOfN(n - 1);
}
content.innerHTML += "The sum of 1 to 10 numbers is " + sumOfN(10) + "<br>";
content.innerHTML += "The sum of 1 to 20 numbers is " + sumOfN(20) + "<br>";
</script>
</body>
</html>
让我们来理解上面的递归函数是如何工作的。在下面,用户可以逐步了解递归函数调用的过程。
sumOfN(5);
return 5 + sumOfN(4);
return 4 + sumOfN(3);
return 3 + sumOfN(2);
return 2 + sumOfN(1);
return 1;
return 2 + 1;
return 3 + 3;
return 4 + 6;
示例3(迭代方法合并数组中的字符串)
在下面的示例中,我们已经创建了字符串数组。我们创建了mergeString()函数,将数组中的所有字符串合并为一个单一字符串。我们使用for循环遍历数组,并逐个将所有字符串合并到’str’变量中。
<html>
<body>
<h3>Using the <i> iterative approach </i> to merge all strings of the array in JavaScript</h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// function to merge all strings of the array using for loop
function mergeString(arr) {
let str = '';
for (let i = 0; i < arr.length; i++) {
str += arr[i];
}
return str;
}
let arr = ['I', ' ', 'am', ' ', 'a', ' ', 'programmer'];
content.innerHTML += "The original array is: " + arr + "<br>";
content.innerHTML += "After merging all strings of the array into the single string is " + mergeString(arr) + "<br>";
</script>
</body>
</html>
示例4(递归方法合并数组中的所有字符串)
我们在下面的示例中将mergeString()函数转换为递归函数。我们获取数组的第一个元素,并将其与mergeString()函数的返回结果合并。mergeString()函数在合并后返回剩下的n-1个数组元素。此外,我们使用slice()方法从数组中删除第一个元素。
当数组中只剩下一个元素时,它返回相同的元素,这起到基本条件的作用。
<html>
<body>
<h3>Using the <i> Recursive approach </i> to merge all strings of the array in JavaScript</h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// function to merge all strings of the array using recursion
function mergeString(arr) {
// based condition
if (arr.length == 1) {
return arr[0];
}
// remove the first element from the array using the slice() method.
return arr[0] + " " + mergeString(arr.slice(1));
}
let arr = ["I", "am", "a", "web", "developer"];
content.innerHTML += "The original array is: " + arr + "<br>";
content.innerHTML += "After merging all strings of the array into the single string is " + mergeString(arr) + "<br>";
</script>
</body>
</html>
用户应该使用哪种方法,迭代还是递归
主要问题是哪种方法更好,迭代还是递归,用户应该使用哪种方法。
在某些情况下,迭代方法比递归方法更快。此外,递归在迭代过程中占用更多内存。对于一些算法,例如分而治之方法,递归更有用,因为我们使用递归方法需要编写更少的代码。此外,如果在递归方法中基本条件不触发,用户可能会面临内存泄漏问题。
如果我们可以将代码分解为较小的部分,应该使用递归方法,为了提高代码性能,应该使用迭代方法。