Array.push() and unique items

后端 未结 12 549
梦谈多话
梦谈多话 2020-12-24 10:45

I have a simple case of pushing unique values into array. It looks like this:

  this.items = [];

  add(item) {
    if(this.items.indexOf(item) > -1) {
           


        
12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 10:50

    Your logic is saying, "if this item exists already, then add it." It should be the opposite of that.

    Change it to...

    if (this.items.indexOf(item) == -1) {
        this.items.push(item);
    }
    

提交回复
热议问题