本篇文章主要是對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>