<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>qc</title> <script src="jquery.1.9.1.min.js"></script> </head> <body> <script> //数组去空值 var arr1=["某某","",3,5,"color","",3,"某某","color",""] console.log(arr1) //拓展数组去空值的方法 Array.prototype.removeEmpty=function () { for(var i=0;i<this.length;i++){ if(this[i]==""||typeof(this[i])=="undefind"){ this.splice(i,1); i--; } } return this; } var arr2=arr1.removeEmpty(); console.log(arr2) </script> <script> //数组去重 var arr3=["比特币","比特币","莱特币","莱特币","66","66",88,88,"",""] var arr4=["比特币","比特币","莱特币","莱特币","66","66",88,88,"",""] //方法一:拓展数组去重的方法 Array.prototype.removeRepeat=function () { var res=[]; var json={}; for(var i=0;i<this.length;i++){ if(!json[this[i]]){ res.push(this[i]); json[this[i]]=1; } } return res; } console.log(arr3.removeRepeat()) //方法二:用es6中set结合Array.from()方法去重 var arr5=new Set(arr4);//这里使用的是Set的一个特性,集合中不会包含重复项。 console.log(arr5) var arr6=Array.from(arr5)//Array.from()是将一个类数组对象或者可遍历对象转换成一个真正的数组 console.log(arr6)
//方法三:用filter()方法去重 var newArr=[]; newArr=arr3.filter(function(ele,index,self){ return self.indexOf(ele)===index; })
</script> </body> </html>
ES6数组去重,去空
最新推荐文章于 2023-07-05 16:46:33 发布