如何改进向数组代码添加/删除项目

时间:2017-03-07 14:40:21

标签: javascript angular typescript ionic2

我有一个项目列表,如果选中或取消选中,我想从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

2 个答案:

答案 0 :(得分:0)

尝试用此替换for - 循环:

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);

答案 1 :(得分: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);