DIV CSS 佈局教程網

JS 陣列去重與取重複項的範例
編輯:JavaScript綜合知識     

本文示範兩種應用:一是去除重複項(去重),二是只取出重複出現的項目(取重)。

方法一:去除重複

<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=[];
  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 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>

第一個方法回傳只保留首次出現的清單,第二個則回傳曾重複出現過的項目(且不再重複列出),可依需求選用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved