推送的递归数组

时间:2016-05-29 20:31:39

标签: javascript arrays recursion

有人可以告诉我在Code Academy问题中我出错的地方。我在Recursion方面遇到了麻烦,我只是模糊地开始理解它在基础层面是如何工作的......第一组代码就是我所写的代码,后面是相同的代码和我尝试过的空白填写。

  

填写空白:multiplyEach()的基本案例编写条件语句。我们希望在堆栈中没有更多值时结束递归。然后我们想要返回变量int,因为它代表了最后一个值。通过递归调用函数完成递归情况,不带任何参数。

填空的空白问题 ___

var stack = [];

function countDown(int) {
  stack.push(int);
  if (int === 1) {  
    return 1;
  }
    return countDown(int - 1);
}

function multiplyEach() {
  // Remove the last value of the stack 
  // and assign it to the variable int
  int = stack.pop();
  x = stack.length;
  // Base case
  if (___) {
    return ___;
  }
  // Recursive case
  else {
    stack[x - 1] = int * stack[x - 1];
    return ___;
  }
}

// Call the function countDown(7)
countDown(7);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());

这是我的尝试:

var stack = [];

function countDown(int) {
  stack.push(int);
  if (int === 1) {  
    return 1;
  }
    return countDown(int - 1);
}

function multiplyEach() {
  // Remove the last value of the stack 
  // and assign it to the variable int
  int = stack.pop(int);
  x = stack.length;
  // Base case
  if (x === 0) {
    return int;
  }
  // Recursive case
  else {
    stack[x - 1] = int * stack[x - 1];
    return multiplyEach(stack);
  }
}

// Call the function countDown(7)
countDown(7);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());

谢谢!

1 个答案:

答案 0 :(得分:4)

你正确地填补了空白!

在您不必触摸的部分代码中只引入了一个错误:

替换:

int = stack.pop(int);

使用:

var int = stack.pop();

因为pop 返回您需要的值。没有必要传递任何东西。

此外,您将stack参数传递给不接受该参数的函数(该变量是全局变量)。这没有坏处,但为了避免混淆,最好不带参数调用函数,因为它应该是:

   return multiplyEach();

对您提供的代码进行了一些侧面评论:

  • 在未来的JavaScript版本中,将变量int命名为might become a reserved word是不好的做法;
  • 同样的变量最好在函数本地声明,因为它现在是在全局范围内创建的。使用varvar int = ...