Array.push() and unique items

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

    so not sure if this answers your question but the indexOf the items you are adding keep returning -1. Not to familiar with js but it appears the items do that because they are not in the array yet. I made a jsfiddle of a little modified code for you.

    this.items = [];
    
    add(1);
    add(2);
    add(3);
    
    document.write("added items to array");
    document.write("
    "); function add(item) { //document.write(this.items.indexOf(item)); if(this.items.indexOf(item) <= -1) { this.items.push(item); //document.write("Hello World!"); } } document.write("array is : " + this.items);

    https://jsfiddle.net/jmpalmisano/Lnommkbw/2/

提交回复
热议问题