本篇文章主要是对 JS 数组去重与取重的示例代码进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
方法一:去重复数据
- <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>
来源: