简体   繁体   English

使用递归在 Javascript 中对一组数字求和

[英]Sum an array of numbers in Javascript using Recursion

Why isn't this working?为什么这不起作用? I'm getting a stack too deep error:我收到一个堆栈太深的错误:

var countRecursion = function(array) {
  var sum = 0
  var count = 0

  sum += array[count]
  count ++

  if (count < array.length) {
    countRecursion(array);
  } else {
    return sum
  }

}

You made a mistake and reset sum and counter inside the recursive block.您犯了一个错误并在递归块内重置 sum 和 counter。 I simply moved them outside.我只是将它们移到外面。

var countRecursion = function(array) {

  sum += array[count]
  count ++

  if (count < array.length) {
    countRecursion(array);
  } else {
    return sum
  }

}

  var sum = 0
  var count = 0


countRecursion([1,2,3]);

alert(sum);

This code is not recursive but iterative.这段代码不是递归的,而是迭代的。 I am not 100% sure if that's what you really wanted.我不能 100% 确定这是否是您真正想要的。 But since you mentioned it, some people down voted my answer since I only fixed your code, but didn't made it recursive I guess.但是既然你提到了它,有些人拒绝了我的答案,因为我只修复了你的代码,但我猜没有让它递归。 For completeness, here is recursive version of your code:为了完整起见,这里是您的代码的递归版本:

var countRecursion = function(array, ind) {


  if (ind < array.length) {
    return array[ind] + countRecursion(array, ind + 1);
  } else {
    return 0;
  }

}

  var sum = 0
  var count = 0


sum = sum + countRecursion([1,2,3, 5, 6, 7], count);

alert(sum);

For recursion: pass data up, return data down.对于递归:向上传递数据,向下返回数据。

The original code has a different count variable, being a local variable defined in the function, that is initial set to 0. As such the base case is never reached and the function recurses until the exception is thrown.原始代码有一个不同的count变量,它是函数中定义的局部变量,初始设置为 0。因此,永远不会达到基本情况,函数会递归,直到抛出异常。

In addition to using a variable from an outer scope (or another side-effect) this can also be addressed by by following the recommendation on how to handle recursion, eg.除了使用来自外部作用域(或其他副作用)的变量之外,这也可以通过遵循有关如何处理递归的建议来解决,例如。

var countRecursion = function(array, index) {
  index = index || 0; // Default to 0 when not specified

  if (index >= array.length) {
     // Base case
     return 0;
  }

  // Recurrence case - add the result to the sum of the current item.
  // The recursive function is supplied the next index so it will eventually terminate.
  return array[index] + countRecursion(array, index + 1);    
}

I see what you're thinking.我明白你在想什么。

The issue with your code is that everytime you call countRecursion , count goes back to 0 (since it's initialized to 0 within your function body).您的代码的问题是每次调用countRecursioncount都会返回到 0(因为它在函数体内初始化为 0)。 This is making countRecursion execute infinitely many times, as you're always coming back to count = 0 and checking the first term.这使得countRecursion无限次执行,因为您总是回到count = 0并检查第一项。 You can solve this by either:您可以通过以下任一方式解决此问题:

  1. Initializing count outside the function body, that way when you do count++ , it increases and doesn't get reset to 0.在函数体外部初始化count ,这样当您执行count++ ,它会增加并且不会重置为 0。
  2. Passing count along with array as a parameter.countarray作为参数传递。 That way, the first time you call the function, you say countRecursion(array, 0) to initialize count for you.这样,第一次调用该函数时,您会说countRecursion(array, 0)来为您初始化count

Note that you have to do the same for sum , else that will also revert to zero always.请注意,您必须对sum执行相同操作,否则它也将始终恢复为零。

Finally, (and this doesn't have to do with the stack error) you have to actually call return countRecursion(array) to actually move up the stack (at least that's how it is in C++ and what not - pretty sure it applies to javascript too though).最后,(这与堆栈错误无关)您必须实际调用return countRecursion(array)以实际向上移动堆栈(至少在 C++ 中是这样,而不是什么 - 很确定它适用于javascript也是)。

Array sum using recursive method使用递归方法的数组和

 var countRecursion = function(arr, current_index) { if(arr.length === current_index) return 0; current_index = current_index || 0; return countRecursion(arr, current_index+1) + arr[current_index]; } document.body.innerHTML = countRecursion([1,2,3,4,5, 6])

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

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