js 去除數組重複值

<script type="text/javascript">
// 去除數組重複值
// 方法1(推薦)-----------利用對象。
var s = ['a','b','c','c','d'];
var o={},tmp=[],count=0,l=s.length;
        for(var i=0;i<l;i++){
        var b = s[i];
                if(o[b] === undefined){//把數組的value當成對象o的key, 訪問key的值
                    // 給對象的key賦值,下次訪問的時候就不會再是undefined
                    o[b]=1;
                    tmp.push(b)
                }
        }
        // 輸出的是 a,b,c,d
        document.write('新數組是:'+tmp);
        // ps:最後對象o是 {a:1, b:1, c:1, d:1}



       // 方法2-----------利用splice()函數。
        Array.prototype.strip=function()
{
if(this.length<2) return [this[0]]||[];
var arr=[];
for(var i=0;i<this.length;i++)
{
arr.push(this.splice(i--,1));
for(var j=0;j<this.length;j++)
{
if(this[j]==arr[arr.length-1])
{
this.splice(j--,1);
}
}
}
return arr;
}
var arr=["abc",85,"abc",85,8,8,1,2,5,4,7,8];
document.write('<br/>'+arr.strip());
</script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章