[JavaScript] JavaScript比较两个对象是否相等 →→→→→进入此内容的聊天室

来自 , 2020-04-03, 写在 JavaScript, 查看 103 次.
URL http://www.code666.cn/view/055e31fa
  1. Object.equals = function( x, y ) {
  2.         // If both x and y are null or undefined and exactly the same
  3.         if ( x === y ) {
  4.             return true;
  5.         }
  6.  
  7.         // If they are not strictly equal, they both need to be Objects
  8.         if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {
  9.             return false;
  10.         }
  11.  
  12.         // They must have the exact same prototype chain, the closest we can do is
  13.         // test the constructor.
  14.         if ( x.constructor !== y.constructor ) {
  15.             return false;
  16.         }
  17.  
  18.         for ( var p in x ) {
  19.             // Inherited properties were tested using x.constructor === y.constructor
  20.             if ( x.hasOwnProperty( p ) ) {
  21.                 // Allows comparing x[ p ] and y[ p ] when set to undefined
  22.                 if ( ! y.hasOwnProperty( p ) ) {
  23.                     return false;
  24.                 }
  25.  
  26.                 // If they have the same strict value or identity then they are equal
  27.                 if ( x[ p ] === y[ p ] ) {
  28.                     continue;
  29.                 }
  30.  
  31.                 // Numbers, Strings, Functions, Booleans must be strictly equal
  32.                 if ( typeof( x[ p ] ) !== "object" ) {
  33.                     return false;
  34.                 }
  35.  
  36.                 // Objects and Arrays must be tested recursively
  37.                 if ( ! Object.equals( x[ p ],  y[ p ] ) ) {
  38.                     return false;
  39.                 }
  40.             }
  41.         }
  42.  
  43.         for ( p in y ) {
  44.             // allows x[ p ] to be set to undefined
  45.             if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {
  46.                 return false;
  47.             }
  48.         }
  49.         return true;
  50.     };
  51. //javascript/1985

回复 "JavaScript比较两个对象是否相等"

这儿你可以回复上面这条便签

captcha