推薦幾種數(shù)組去重的方法
<script type="text/javascript">
var a=["1","2","3","4","5"];
var b=["7","2","1","8","9"];
//var newArray=distinct1(a,b);
var newArray=distinct2(a,b);
//var newArray=distinct3(a,b);
console.log(newArray)
//方式1 for循環(huán)(傳統(tǒng)寫法)
function distinct1(a,b){
var arryDiff=[];
for(var i=0;i<a.length;i++){
for(var j=0;j<b.length; j++){
if(a[i]==b[j]){
b.splice(j,1);
}
}
}
arryDiff=a.concat(b);
return arryDiff;
}
//方式2 利用indexof
function distinct2(a,b){
var arryDiff=[];
a.map(item=>{
if(b.indexOf(item)==-1){
b.push(item);
arryDiff=b;
}
})
return arryDiff;
}
//方式3 最簡便的
function distinct3(a,b){
var arryDiff=[];
arryDiff=new Set([...a,...b]);
return arryDiff;
}
</script>