我真的需要反馈我的解释,尤其是 2) 和 3)。我只是想确认一下我是否理解正确,因为我是新手。这是一个 freeCodeCamp 挑战,对我来说确实很有挑战性,因为我以前没有 JS 经验。如下所示。编写一个递归函数 sum(arr, n),返回数组 arr 的前 n 个元素的总和。function sum(arr, n) { if(n <= 0) { return 0; } else { return sum(arr, n - 1) + arr[n - 1]; }}/* 1) sum([1], 0) should equal 0. 2) sum([2, 3, 4], 1) should equal 2. 3) sum([2, 3, 4, 5], 3) should equal 9. *//* My explanations are down below *//* Explanation 1) sum([1], 0) should equal 0. n is less or equal to 0 so line 2 works and returns 0 at line 3.*//* Explanation 2) sum([2, 3, 4], 1) should equal 2 n is not less or equal to 0 so it will not return 0 according to line 2. We move to line 5. *return sum(arr, n - 1) + arr[n - 1];=> return sum([2, 3, 4], 1 - 1) + arr[1 - 1];=> return sum([2, 3, 4], 0) + arr[0] => n is less or equal to 0 so it will return zero according to line 2.=> return 0 + arr[0]=> Since arr[0] is equals to 2=> return 0 + 2;=> 2*//* Explanation 3) sum([2, 3, 4, 5], 3) should equal 9 n is not less or equal to 0 so it will not return 0 according to line 2. We move to line 5. *return sum(arr, n - 1) + arr[n - 1];=> return sum([2, 3, 4, 5], 3 - 1) + arr[3 - 1];=> return sum([2, 3, 4, 5], 2) + arr[2]; => n is 2, not less or equal to 0 so go back to line 5 + arr[2].=> return sum(arr, n - 1) + arr[n - 1] + arr[2];=> return sum([2, 3, 4, 5], 2 - 1) + arr[2 - 1] + arr[2];=> return sum([2, 3, 4, 5], 1) + arr[1] + arr[2]; => n is 1, not less or equal to 0 so goes back to line 5 arr[1] + arr[2].=> return sum(arr, n - 1) + arr[n - 1] + arr[1] + arr[2];=> return sum([2, 3, 4, 5], 1 - 1) + arr[1 - 1] + arr[1] + arr[2];=> return sum([2, 3, 4, 5], 0) + arr [0] + arr[1] + arr[2];=> return 0 + arr[0] + arr[1] + arr[2];=> in our array, arr[0] is 2, arr[1] is 3, arr[2] is 4.=> 0 + 2 + 3 + 4=> 5 + 4=> returns 9*/
2 回答
慕侠2389804
TA贡献1719条经验 获得超6个赞
从逻辑角度来看,它看起来不错。如果你想玩一下,你也可以尝试三元运算符。
return n <= 0 ? 0 : sum(arr, n - 1) + arr[n - 1];
第一个块是 if 问题。如果为真,则转到第二个块(以 : 开头),如果为假,则转到第三个块(以 : 开头)。
SMILET
TA贡献1796条经验 获得超4个赞
我认为我们无法缩短它:
const sum = (arr,n) => --n<0 ? 0 : sum(arr,n) +arr[n]
console.log ( sum([1], 0) )
console.log ( sum([2, 3, 4], 1) )
console.log ( sum([2, 3, 4, 5], 3) )
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报
0/150
提交
取消