陣列去空,去重
阿新 • • 發佈:2019-01-22
<!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) </script> </body> </html>