2016-12-18 12 views
1

私は、ツリークラスを構築することでJavaScriptでいくつかの練習をしようとしています。私は再帰的にツリーの葉を取得しようとする関数でいくつかの奇妙な問題を抱えています。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はすべてのインスタンスで共有されていますか?だから私はそれをプロトタイプではなくTreeオブジェクト内のメソッドとしてget_leavesを定義する必要がありますか? (これを行うことは非効率的なので、私はより良い方法があると思っていました)。ありがとう!

答えて

1

何らかの理由で変数宣言にvarを使用していないため、branchesというのはローカル変数ではなくグローバル変数です。あなたのコードに簡単な修正は次のようにbranchesvarを追加することです:今、完全に働いた

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

おっとを。 Pythonは変数宣言hahaなしで私を台無しにしました。ありがとう! –

+0

実際、Pythonのような言語は、_convenient_へのwaaayであり、それほど素晴らしいコーディング習慣を開発していません。お力になれて、嬉しいです :) –