免费模板网标签tags 更多...
您的位置:首页 > javascript学习 > 怎么通过javascript取出数组中不重复的元素

怎么通过javascript取出数组中不重复的元素

时间:2016-08-30 来源:网上收集 作者:Tony 阅读次数 tags数组js

类似php语言一样,在一个数组里面有重复的元素,要去除怎么写代码呢,请看下文

<script type="text/javascript"> 
var ret= ["span","span","strong","span","b"] 
var norepeat = function(array){ 
var set = array.join(",")+","; 
while(array.length){ 
var el = array.shift(); 
set = set.replace(el+",",""); 
if(set.indexOf(el+",") != -1){ 
set = set.replace(new RegExp(el+",","g"),""); 
array = set.replace(/,$/g,"").split(","); 
}else{ 
set = el+","+set; 
return set.replace(/,$/g,"").split(",") 
alert(norepeat(ret))//最后返回b,strong 
</script>

demo2
 
<script language="javascript">
var ret= ["span","span","strong","span","b"]; 
var norepeat=function (x) { 
var y='c0cb5f0fcf239ab3d9c1fcd31fff1efc'; 
return x.sort().join(y).replace(RegExp('(.*('+y+'|$))\\1+','g'),'').split(y); 
}; 
alert(norepeat(ret)); 
</script>

demo3
<script language="javascript"> 
Array.prototype.inArray = function(el){ 
for (var i=0,n=this.length;i<n;i++ ) 
if(this[i]===el)return true; 
return false; 
Array.prototype.unique = function() { 
var i = 0, n = this.length,ret = []; 
for (; i < n; i++) 
if (!ret.inArray(this[i])) ret.push(this[i]); 
return ret; 
}; 
var ret= ["span","span","strong","span","b"] 
alert(ret.unique()) //返回"span","strong","b" 
</script>
 

猜你喜欢
栏目推荐
模板推荐

Copyright:2014-2018 www.freemoban.com Corporation,All Rights Reserved 免费模板网 版权所有 鄂ICP备17019132号

免责声明:本站部分资源来自互联网收集,版权归原创者所有,如果侵犯了你的权益,请通知我们,我们会及时删除侵权内容,谢谢合作!

建站咨询QQ