2016-12-18 3 views
1

Так что я пытаюсь получить некоторую практику в javascript, создав древовидный класс. У меня возникают некоторые странные проблемы с функцией, в которой я пытаюсь рекурсивно получить листья дерева.Javascript Array Recursion

Например,

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, а не в его прототипе? (кажется, неэффективно это делать, поэтому я надеялся, что есть лучший способ). Благодаря!

ответ

1

По какой-то причине вы не используете 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();

+1

Oops, которые работали совершенно теперь. Python испортил мне без объявления переменной haha. Благодаря! –

+0

Ха-ха, действительно, языки, подобные Python, являются waaay to _convenient_ :) и развивают не очень приятные привычки кодирования. Рад был помочь :) –