• javascript 返回数组中不重复的元素


    这是实现结构伪类type-of-type的部分代码: 

    <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>

    觉得效果不高,向无忧高手求救。下面是客服果果的(好强大的正则替换啊): 


    <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>

    abcdreamer 的实现(此实现能过滤非纯字符串数组里的重复,我比较喜欢):


    <script language="javascript">
    var a = ["span","span","strong","span","b"];
    function norepeat(a) {
    var i = a.length, j, b;
    while (i--) {
    j = i;
    b = false;
    while (j--) {
    if (a[i] === a[j]) {
    a.splice(j, 1);
    i--;
    b = true;
    }
    }
    if (b) a.splice(i, 1);
    }
    return a;
    }
    alert(norepeat(a));
    </script>

    哪位高手有更好的实现,请告诉我一声! 
    看来有些人不明白norepeat函数与unique函数的区别,norepeat是去除数组中重复的元素,如果数组中有两个a,则去除这两个,unique则会去除其中之一。下面是unique函数的实现: 

    <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>

  • 相关阅读:
    C++ vector介绍
    C++string的使用
    关于VS2010error RC2170 : bitmap file res mp1.bmp is not in 3.00 format
    团队项目第一次讨论
    团队项目——铁大树洞个人分析
    第五周学习进度总结
    转发
    android移动端疫情展示
    《构建之法》阅读笔记03
    第四周学习进度总结
  • 原文地址:https://www.cnblogs.com/mili3/p/4554566.html
Copyright © 2020-2023  润新知