使用递归返回数组 arr 的前 n 个元素的总和 [英] Using recursion to return the sum of the first n elements of an array arr

查看:58
本文介绍了使用递归返回数组 arr 的前 n 个元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 freecodecamp.org 学习一些 JavaScript,但我偶然发现了一个我无法解决的递归问题:

I'm trying to learn some JavaScript from freecodecamp.org and I stumbled upon a recursion problem which I can't wrap my head around:

说明:编写一个递归函数 sum(arr, n),它返回数组 arr 的前 n 个元素的总和.

Instructions: Write a recursive function, sum(arr, n), that returns the sum of the first n elements of an array arr.

function sum(arr, n) {
  if(n <= 0) {
    return 0;
  } else {
    return sum(arr, n - 1) + arr[n - 1];
  }
}

我理解第二部分:arr[n -1] 添加项目值

I understand the second part: arr[n -1] adding the item value

但我不明白第一部分(sum(arr, n-1)) 的作用,以及 arr 参数如何反应.

But I don't understand what the first part(sum(arr, n-1)) does, and how the arr parameter reacts.

有人可以帮忙吗?

感谢任何帮助!

推荐答案

执行此代码时,您会创建一个由 frames 组成的 stack.

When executing this code, you create a stack composed with frames.

每一个都是一个函数调用,帧数为n + 1.

Every frame is a function call, the number of frames is n + 1.

无关:StackOverflow 是当堆栈大小超过某个限制时发生的常见错误的名称.

Unrelated: StackOverflow is the name of a common error that happens when the stack size goes beyond a certain limit.

例如,如果您将 [1, 2, 3, 4, 5, 6, 7, 8, 9]4 作为参数传递,则隐式创建以下堆栈从下到上:

For example, if you pass [1, 2, 3, 4, 5, 6, 7, 8, 9] and 4 as parameters, you create implicitly the following stack from bottom to top:

sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 0) // This resolves first as it doesn't need to call sum again: 0
sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 1) // Then this: 0 + 1 = 1
sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) // Then this: 1 + 2 = 3
sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) // Then this: 3 + 3 = 6
sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) // Then you get the final result: 6 + 4 = 10

这篇关于使用递归返回数组 arr 的前 n 个元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆