Javascript 递归? [英] Javascript Recursion?

查看:50
本文介绍了Javascript 递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习递归.从概念上讲,我理解这应该如何工作(见下文),但我的代码不起作用.

I am practicing recursion. Conceptually I understand how this should work, (see below) but my code isn't working.

请告诉我我做错了什么.并请解释您代码的每一步以及它是如何工作的.清晰的解释比只给我有效的代码要好十倍.

Please tell me what I am doing wrong. And please explain each step of your code and how it works. Clear Explanation is ten times better than just giving me code that works.

  /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var buildList = function(value, length) {
    var result = [];
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};


buildList(0, 5);

我理解递归在概念层面是如何工作的.

I understand how recursion works on a conceptual level.

推荐答案

你的方法行不通,因为基本情况返回一个新的空数组,其他情况返回递归的结果.

Your approach can't work, because the base case returns a new empty array, and other cases return the result of the recursion.

相反,你应该先递归再推送

Instead, you should first recurse and then push

var buildList = function(value, length) {
  if (length <= 0) return [];
  var recur = buildList(value, length-1);
  recur.push(value);
  return recur;
};

或者,在基本情况下,您可以避免创建新数组

Alternatively, in the base case you can avoid creating a new array

var buildList = function(value, length, array=[]) {
  if (length <= 0) return array;
  array.push(value);
  return buildList(value, length-1, array);
};

这篇关于Javascript 递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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