Array.push() and unique items

后端 未结 12 573
梦谈多话
梦谈多话 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 11:06

    try .includes()

    [1, 2, 3].includes(2);     // true
    [1, 2, 3].includes(4);     // false
    [1, 2, 3].includes(3, 3);  // false
    [1, 2, 3].includes(3, -1); // true
    [1, 2, NaN].includes(NaN); // true
    

    so something like

    const array = [1, 3];
    if (!array.includes(2))
        array.push(2);
    

    note the browser compatibility at the bottom of the page, however.

提交回复
热议问题