2017-10-06 39 views
-1

我有以下打字稿功能:爲什麼在這個函數的末尾沒有這個數組?

setSelectedTagsFilters(tags) 
{ 
    //init return var 
    var selectedTags = []; 

    //set selected tags filters 
    if (tags && tags.length > 0) 
    { 
     //required for parent context from for loop 
     let that = this; 

     //for each tag qs param 
     for (let tag of tags) 
     { 
      //lookup matches 
      var matches; 
      if (isNumeric(tag)) matches = that.vm.AllTags.filter(x => x.id == tag); 
      else matches = that.vm.AllTags.filter(x => x.text == tag); 

      //if match then add to selectedTags 
      if (matches.length == 0) selectedTags.push(matches[0]); 
     } 
    } 
    //set the tag filters in batch 
    this.setTagFilters(selectedTags); 
} 

我有哪裏2場比賽都推到選定的標籤的情況。但是,在最後一行代碼中,selectedTags是一個空數組。任何想法爲什麼selectedTags在方法的末尾是空的,即使2個對象被推送到for循環中的selectedTags?

+0

你試過調試嗎? –

+0

這條線看起來像一個問題:'if(matches.length == 0)selectedTags.push(matches [0]);' – JohnnyHK

+0

@JohnnyHK那條線看起來有什麼問題?我已經證實,在推後的代碼行中,selectedTags仍然是空的。但爲什麼?我該如何解決? – user8570495

回答

0

這條線:

if (matches.length == 0) selectedTags.push(matches[0]); 

是錯誤的。如果matches.length==0,matches[0]未定義,也沒有任何東西被推送到selectedTags

嘗試:

if (matches.length > 0) selectedTags.push(matches[0]); 

代替。

+0

是的,我在週五重構和打字時迷路了。謝謝! – user8570495

相關問題