国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JS實現的Object數組去重功能示例【數組成員為Object對象】

2024-05-06 15:42:39
字體:
來源:轉載
供稿:網友

本文實例講述了JS實現的Object數組去重功能。分享給大家供大家參考,具體如下:

目標:實現成員為 Object 的數組的去重。

注意,這里的數組成員為 Object,而不是數值或者字符串。

調用方法:

arr = distinct_arr_element(arr);

函數:

/* * 在數組中去除重復項() */var distinct_arr_element = function( arr ){  if( !arr ) return null ;  var resultArr = [];  $(arr).each( function( index, el ){    var notExist = true ;    $(resultArr).each( function(i,element){      if( isObjectValueEqual( el, element ) ){        notExist = false ;        return false ;      }    });    if( notExist )      resultArr.push( el );  });  return resultArr ;}/* * 判斷兩個 Object 的值是否相等 */function isObjectValueEqual(a, b) {  // Of course, we can do it use for in Create arrays of property names  var aProps = Object.getOwnPropertyNames(a);  var bProps = Object.getOwnPropertyNames(b);  // If number of properties is different, objects are not equivalent  if (aProps.length != bProps.length) {    return false;  }  for ( var i = 0; i < aProps.length; i++ ) {    var propName = aProps[i];    // If values of same property are not equal, objects are not equivalent    if (a[propName] !== b[propName]) {      return false;    }  }  // If we made it this far, objects are considered equivalent  return true;}

完整測試示例如下:

<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script><script>/* * 在數組中去除重復項() */var distinct_arr_element = function( arr ){  if( !arr ) return null ;  var resultArr = [];  $(arr).each( function( index, el ){    var notExist = true ;    $(resultArr).each( function(i,element){      if( isObjectValueEqual( el, element ) ){        notExist = false ;        return false ;      }    });    if( notExist )       resultArr.push( el );  });  return resultArr ;}/* * 判斷兩個 Object 的值是否相等 */function isObjectValueEqual(a, b) {  // Of course, we can do it use for in Create arrays of property names  var aProps = Object.getOwnPropertyNames(a);  var bProps = Object.getOwnPropertyNames(b);  // If number of properties is different, objects are not equivalent  if (aProps.length != bProps.length) {    return false;  }  for ( var i = 0; i < aProps.length; i++ ) {    var propName = aProps[i];    // If values of same property are not equal, objects are not equivalent    if (a[propName] !== b[propName]) {      return false;    }  }  // If we made it this far, objects are considered equivalent  return true;}var arrDemo=[{'name':'Vevb.com'},{'name':'Vevb.com'},{'age':10},{'age':12}];console.log(distinct_arr_element(arrDemo))</script>

使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.Vevb.com/code/HtmlJsRun測試上述代碼,可得如下運行結果:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 丁青县| 崇州市| 新乡县| 莱芜市| 大埔县| 泸西县| 绥芬河市| 娱乐| 汽车| 商水县| 苗栗市| 正镶白旗| 葫芦岛市| 毕节市| 上虞市| 肃宁县| 高陵县| 九龙城区| 娱乐| 城口县| 北票市| 大悟县| 湘西| 双辽市| 乐清市| 连云港市| 江口县| 马尔康县| 灵石县| 墨竹工卡县| 田阳县| 聂拉木县| 兰西县| 安吉县| 景谷| 聂荣县| 云林县| 科尔| 昌吉市| 新巴尔虎右旗| 罗城|