这是实现结构伪类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>