2017-06-21 19 views
1

我想調用filterArr中的filterArr。這是我的實現。如何在typescipt中遞歸調用方法

filterArr(array, search) { 
     var result = []; 
     array.forEach((a)=> { 
      var temp = [], 
       o = {}, 
       found = false; 

      if (a.name === search) { 
       this.o.name = a.name; 
       found = true; 
      } 
      if (Array.isArray(a.children)) { 
       temp = this.filterArr(a.children, search);//***Cannot read property 'filterArr' of undefined*** 
       if (temp.length) { 
        this.o.children = temp; 
        found = true; 
       } 
      } 
      if (found) { 
       result.push(o); 
      } 
     }); 
     return result; 
    } 

如何調用filterArr方法沒有任何錯誤?

+0

是否顯示任何警告如果刪除了''的這部分this.' .filterArr(a.children,search)'? –

+2

[如何在回調中訪問正確的\'this \'上下文的可能的副本?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside- a-callback) – echonax

+0

是的,它顯示錯誤,當我刪除這個 –

回答

2

你必須使用Arrow function得到堅持正確this,所以你需要改變array.forEach(function (a) {使用`Arrow功能

array.forEach((a) => {