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

首頁 > 編程 > JavaScript > 正文

JavaScript比較兩個對象是否相等的方法

2019-11-20 13:12:41
字體:
來源:轉載
供稿:網友

本文實例講述了JavaScript比較兩個對象是否相等的方法。分享給大家供大家參考。具體如下:

在Python中可以通過cmp()內建函數來比較兩個對象所包涵的數據是否相等(數組、序列、字典)。但是在javascript語言中并沒有相關的實現。本js代碼通過對js對象進行各方面的比較來判斷兩個對象是否相等

cmp = function( x, y ) { // If both x and y are null or undefined and exactly the same if ( x === y ) {  return true; } // If they are not strictly equal, they both need to be Objects if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {  return false; } //They must have the exact same prototype chain,the closest we can do is//test the constructor. if ( x.constructor !== y.constructor ) {  return false; }  for ( var p in x ) {  //Inherited properties were tested using x.constructor === y.constructor if ( x.hasOwnProperty( p ) ) {  // Allows comparing x[ p ] and y[ p ] when set to undefined  if ( ! y.hasOwnProperty( p ) ) {   return false;  }  // If they have the same strict value or identity then they are equal  if ( x[ p ] === y[ p ] ) {   continue;  }  // Numbers, Strings, Functions, Booleans must be strictly equal  if ( typeof( x[ p ] ) !== "object" ) {   return false;  }  // Objects and Arrays must be tested recursively  if ( ! Object.equals( x[ p ], y[ p ] ) ) {   return false;  }  } } for ( p in y ) {  // allows x[ p ] to be set to undefined  if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {  return false;  } } return true; };

使用:

objA={  a:'123',  b:'456' }; objB={  a:'123',  b:'000' }; var isEqual= cmp(objA, objB);  console.log(isEqual);  // false 不相同

希望本文所述對大家的javascript程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 上林县| 凌云县| 黎川县| 包头市| 如东县| 西乌珠穆沁旗| 偏关县| 顺义区| 梓潼县| 龙胜| 修武县| 隆安县| 桂阳县| 汉寿县| 南涧| 栾城县| 电白县| 林西县| 益阳市| 镇原县| 乐山市| 浪卡子县| 呼图壁县| 广州市| 礼泉县| 望奎县| 玉林市| 丹凤县| 桃源县| 合山市| 鲁山县| 汝阳县| 方城县| 繁昌县| 德江县| 安远县| 江川县| 基隆市| 溧阳市| 巍山| 韩城市|