JS数组去重与取重的示例代码
更新时间:2014年01月24日 09:31:35 作者:
本篇文章主要是对JS数组去重与取重的示例代码进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助
方法一:去重复数据
<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>
复制代码 代码如下:
<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解析xml字符串和xml文档实现原理及代码(针对ie与火狐)
分别针对ie和火狐分别作了对xml文档和xml字符串的解析,考虑到了浏览器的兼容性,至于在ajax环境下解析xml,其实原理是一样的,只不过放在了ajax里,还是要对返回的xml进行解析,感兴趣的朋友可以了解下,或许对你学习js解析xml有所帮助2013-02-02JavaScript使用shift方法移除素组第一个元素实例分析
这篇文章主要介绍了JavaScript使用shift方法移除素组第一个元素的用法,实例分析了javascript中shift方法的使用技巧,需要的朋友可以参考下2015-04-04Bootstrap中的fileinput 多图片上传及编辑功能
这篇文章主要介绍了Bootstrap中的fileinput 多图片上传及编辑功能的实现,非常不错,具有参考借鉴价值,需要的朋友可以参考下2016-09-09
最新评论