JavaScript 数组递归

标签 javascript recursion tree prototype

所以我试图通过构建一个树类来练习 javascript。我在尝试递归获取树的叶子的函数中遇到了一些奇怪的问题。

例如,

  function Tree(root, branches){ 
      this.root = root;
      this.branches = branches;
    }


    t = new Tree(2, [new Tree(6), new Tree(5)]); 

    Tree.prototype.is_leaf = function(){
      return !(this.branches)
    }

    Tree.prototype.get_leaves = function(){
      mainTree = this;
      root = this.root;
      branches = this.branches
      list_of_leaves = []

      if(mainTree.is_leaf()){
        list_of_leaves.push(root);
      } else {
          for(i = 0; i < branches.length; i++){ //go through each branch and run get_leaves
            console.log(branches); //Branches logs correctly here
            list_of_leaves.push.apply(list_of_leaves, branches[i].get_leaves()); 
             /*extend the main list_of_leaves with the list of leaves of each branch (THIS LINE CAUSES THE PROBLEM)*/
            console.log(branches); //Branches is set to undefined here
          }
      }
      return list_of_leaves;
    }

    t.get_leaves();

当我尝试运行此函数时,出现“分支长度未定义”错误。由于某种原因,分支通过递归调用而发生变异,我不明白为什么会发生这种情况。数组中的 list_of_leaves 是否在所有实例之间共享?那么我应该将 get_leaves 定义为 Tree 对象中的方法而不是其原型(prototype)中的方法吗? (这样做似乎效率很低,所以我希望有更好的方法)。谢谢!

最佳答案

由于某种原因,您没有使用 var 进行变量声明,这会导致 branches 不是本地变量而是全局变量。对代码的快速修复是将 var 添加到 branches 中,如下所示:

  function Tree(root, branches){ 
      this.root = root;
      this.branches = branches;
    }


    t = new Tree(2, [new Tree(6), new Tree(5)]); 

    Tree.prototype.is_leaf = function(){
      return !(this.branches)
    }

    Tree.prototype.get_leaves = function(){
      mainTree = this;
      root = this.root;
      var branches = this.branches; // <--- This line ;)
      list_of_leaves = []

      if(mainTree.is_leaf()){
        list_of_leaves.push(root);
      } else {
          for(i = 0; i < branches.length; i++){ //go through each branch and run get_leaves
            console.log(branches); //Branches logs correctly here
            list_of_leaves.push.apply(list_of_leaves, branches[i].get_leaves()); 
             /*extend the main list_of_leaves with the list of leaves of each branch (THIS LINE CAUSES THE PROBLEM)*/
            console.log(branches); //Branches is set to undefined here
          }
      }
      return list_of_leaves;
    }

    t.get_leaves();

关于JavaScript 数组递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206325/

相关文章:

javascript - 尝试使用 jQuery 在点击时切换 iframe YouTube 视频的 URL

java - 使用 MacLaurin 级数的递归方法来计算 e^x

javascript - 尾递归二叉树搜索函数JS

linux - 递归计算Linux中所有嵌套子目录中的文件

javascript - Json 中的解析函数

javascript - 尝试画一个书架(可汗学院练习)

javascript - Angular.js ng-focus 和 ng-bind 表达式

python - 递归地将pymysql Comment对象转换为树

c# - 将递归转换为迭代

c++ - 区间树中链表元素的插入