JS数组去重的两种方法

JS利用正则表达式和match()方法去掉数组里的重复元素

数组去重-正则表达式

  1. Array.prototype.unique = function () { //array原型扩展  
  2.     return this.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");  
  3. }  
  4. //使用方法举例 
  5. var arr = ["a","b","c","a","d","e","c","f","d"];  
  6. var newArr = arr.unique(); //["a","b","c","d","e","f"]

数组去重-match()方法

  1. function ArrUnique(arr){ 
  2.     var newArr = []; 
  3.     for(var i=0;i< arr.length;i++){ 
  4.         if(newArr.toString().match(arr[i]) == null){ 
  5.             newArr.push(arr[i]); 
  6.         } 
  7.     } 
  8.     return newArr; 
  9. var myArr=["a","b","c","a","d","e","c","f","d"]; 
  10. var myNewArr = ArrUnique(myArr); //["a","b","c","d","e","f"]

说明:toString()数组转换成字符串;match()匹配字符串,返回值:null或匹配到的字符串;如果返回null表示该字符串没有重复,进而push()追加到新的数组里。

 

相关经验

导读书签
书签初始化中…