简体   繁体   English

为什么递归在两个例子中表现不同?

[英]Why recursion behave differently in the two examples?

I have two examples of recursion, one calculate the sum of all elements of the array and the second return the count, both examples behave differently and i can't relate!我有两个递归示例,一个计算数组所有元素的总和,第二个返回计数,两个示例的行为不同,我无法联系!

First Example:第一个例子:

 const sum = (list) => { if (list.length === 0) { return 0; } return list[0] + sum(list.slice(1)); }; console.log(sum([1, 2, 3, 4])); // 10

The second:第二:

 const count = (list) => { if (list.length === 0) { return 0; } return 1 + count(list.slice(1)); }; console.log(count([0, 1, 2, 3, 4, 5])); // 6

Why the first recursion go through all array elements adding every element while the other added 1 to each element then returned just the final value??为什么第一个递归遍历所有数组元素添加每个元素,而另一个向每个元素添加 1 然后只返回最终值? i assumed it would do the same and the difference would be just adding 1 to the sum!!我认为它会做同样的事情,区别只是在总和上加 1 !

Look at return 1 + count(list.slice(1));看看return 1 + count(list.slice(1)); in the count function.在计数函数中。 It would just ignore the 1st element in the list you pass recursively to the function and always use 1. Versus the sum function does consider that element.它只会忽略您以递归方式传递给函数的列表中的第一个元素,并始终使用 1。而 sum 函数确实会考虑该元素。 That effectively returns the count of times the function has been called which is 6这有效地返回了函数被调用的次数,即 6

1st - sum,2nd - count,如果你希望他们做同样的事情,你应该只使用其中的一个。

The recursion is the same.递归是一样的。

It visits all elements of the array and returns zero if no element is available.它访问数组的所有元素,如果没有可用元素,则返回零。

For each element, it returns either the item for summing or one for counting.对于每个元素,它返回求和项或计数项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM