如何在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时,它返回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>

用户应该使用哪种方法,迭代还是递归?

主要问题是哪种方法更好,迭代还是递归,用户应该使用哪种方法。

在某些情况下,迭代方法比递归方法更快。此外,递归比迭代占用更多内存。对于某些算法(如分治法),递归更有用,因为我们需要使用递归方法编写更少的代码。此外,如果基本条件没有在递归方法中触发,用户可能会遇到内存泄漏问题。

如果我们可以将代码分解成更小的部分,我们应该使用递归方法,为了提高代码的性能,我们应该使用迭代方法。

更新于:2023年3月9日

浏览量:163

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.