js array does not add elements repeatedly

1 Introduction

Since the use of JS push will cause elements to be repeated, and there is no set (collection) method before ES5, repeated elements need to be deduplicated, which is more troublesome, so write a new push directly to deal with it.

2 code

Array.prototype.push2 =function(){
      for(var i=0; i<arguments.length; i++){
        var ele = args [i];
        if(this.indexOf(ele) == -1){
            this.push(ele);
        }
    }
}; 

Description: Just add the method directly on the Array method prototype

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326043969&siteId=291194637