2017-03-07 52 views
0

我有一個項目列表,如果選擇或取消選擇,我想從myStock刪除或添加項目。我遇到的問題是一旦選擇了一個項目瀏覽器就會崩潰。我能更好地做到這一點嗎?我該如何改進向陣列代碼添加/刪除項目

HTML:

<ion-list> 
      <div *ngFor="let item of stockList | speciesSearchPipe:listFilter.value"> 
       <ion-item> 
        <ion-label> 
         {{ item.name_eng }} 
         <img src="./assets/images/species_icons/{{item.image_file}}" width="60" style="float: right;"/> 
        </ion-label> 
        <ion-checkbox class="item-avatar item-checkbox-right" color="dark" checked="false" (click)="selectSpecie(item)"></ion-checkbox> 
       </ion-item> 
      </div> 
    </ion-list> 

TS:

let myStock = this.apiService.currentUser.data.coop.jdata; 
     if (myStock) { 
      for (let x = 0; myStock.stocklist.length > x; x++) { 
       myStock.stocklist["fish_species_id"] === item.fish_species_id ? myStock.stocklist.splice(x,1) : myStock.stocklist.push(item); 
      }; 
     } else { 
      myStock = {}; 
      myStock["stocklist"] = []; 
      myStock.stocklist.push(item); 
     }; 

     console.log(myStock); // First log is as expected, then the app freezes 
+0

什麼是'jdata'? – evolutionxbox

+0

函數'selectSpecie(item)'在哪裏? – Arg0n

回答

0

嘗試更換您的for -loop本:

let index = myStock.stocklist.indexOf(item); 
if(index >= 0) { 
    myStock.stocklist.splice(index, 1); 
} else { 
    myStock.stocklist.push(item); 
} 

全碼:

let myStock = this.apiService.currentUser.data.coop.jdata; 
if (myStock) { 
    let index = myStock.stocklist.indexOf(item); 
    if (index >= 0) { 
     myStock.stocklist.splice(index, 1); 
    } else { 
     myStock.stocklist.push(item); 
    } 
} else { 
    myStock = {}; 
    myStock["stocklist"] = []; 
    myStock.stocklist.push(item); 
}; 

console.log(myStock); 
0
if (!myStock) { 
    myStock = { 
    stockList: [item] 
    }; 
} else { 
    const index = myStock.stockList.findIndex(({item.fish_species_id}) => item.fish_species_id === item.fish_species_id); 
    if(index !== -1) { 
    myStock.stockList[index] = item; 
    } else { 
    myStock.stockList.push(item); 
    } 
} 
console.log(myStock);