推荐几种数组去重的方法
<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循环(传统写法)
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>
网友评论