JS数组去重与取重的示例代码

2019-12-24,,

方法一:去重复数据
复制代码 代码如下:
<script>
Array.prototype.distinct=function(){
var a=[],b=[];
for(var prop in this){
   var d = this[prop];
   if (d===a[prop]) continue; //防止循环到prototype
   if (b[d]!=1){
    a.push(d);
    b[d]=1;
   }
}
return a;
}
var x=['a','b','c','d','b','a','e','a','b','c','d','b','a','e'];
document.write('原始数组:'+x);
document.write("<br />");
document.write('去重复后:'+x.distinct());
</script>

方法二:取重复数据
复制代码 代码如下:
<script type="text/javascript">
Array.prototype.distinct=function(){
   var a=[],b=[],c=[],d=[];
   for(var prop in this){
    var d = this[prop];
    if (d===a[prop])
    {
    continue;
    }//防止循环到prototype
    if (b[d]!=1){
     a.push(d);
     b[d]=1;
    }
    else {

     c.push(d);
     d[d]=1;
    }
   }
   //return a;
   return c.distinct1();
}
Array.prototype.distinct1=function(){
var a=[],b=[];
for(var prop in this){
   var d = this[prop];
   if (d===a[prop]) continue; //防止循环到prototype
   if (b[d]!=1){
    a.push(d);
    b[d]=1;
   }
}
return a;
}
var x=['a','b','c','d','b','a','e','a','b','c','d','b','a','e','f','f','g'];
document.write('原始数组:'+x);
document.write("<br />");
document.write('去重复后:'+x.distinct());
</script>

您可能感兴趣的文章:

  • js数组去重的三种常用方法总结
  • JS实现数组去重方法总结(六种方法)
  • JavaScript数组去重的两种方法推荐
  • js实现数组去重、判断数组以及对象中的内容是否相同
  • js算法中的排序、数组去重详细概述
  • javascript数组去重3种方法的性能测试与比较
  • javascript数字数组去重复项的实现代码
  • js indexOf()定义和用法
  • JavaScript Array对象扩展indexOf()方法
  • JavaScript从数组的indexOf()深入之Object的Property机制
  • JavaScript使用indexOf()实现数组去重的方法分析

《JS数组去重与取重的示例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。