Array.push() and unique items

后端 未结 12 489
梦谈多话
梦谈多话 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:51

    You have to use === -1, if it equals to -1 i.e. item is not available in your array:

      this.items = [];
    
      add(item) {
        if(this.items.indexOf(item) === -1) {
          this.items.push(item);
          console.log(this.items);
        }
      }
    

提交回复
热议问题