JS递归
求数组前n个数的乘积:
function multiply(arr, n) { if (n <= 0) { return 1; //1乘任何数都不会有加成,对结果没有影响。 } else { return multiply(arr, n - 1) * arr[n - 1]; } }
求数组前n个数的累加和:
function sum(arr, n) { if (n<=0) { return 0; //0加任何数都不会有加成,对结果没有影响。 } else { return sum(arr,n-1)+arr[n-1]; } } console.log(sum([1,2,5],3));//结果为8。
以下对乘法的递归进行解析:
The recursive version of multiply breaks down like this. In the base case, where n <= 0, it returns 1. For larger values of n, it calls itself, but with n - 1. That function call is evaluated in the same way, calling multiply again until n <= 0. At this point, all the functions can return and the original multiply returns the answer.
乘法的递归版本如下所示。在基本情况下,其中n<=0,它返回1。对于较大的n值,它调用自己,但使用n-1。该函数调用以相同的方式计算,再次调用乘法,直到n<=1。此时,所有函数都可以返回,原始乘法返回答案。
Note:Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0), otherwise they can never finish executing.
注意:当递归函数返回而不再次调用函数时(在本例中,当n<=0时),必须有一个基本情况,否则它们永远无法完成执行。