对象深比较

深藏阁楼爱情的钟 2022-05-29 01:53 255阅读 0赞

参考自:https://jsperf.com/deep-compare/4

  1. Object.equals = function( x, y ) {
  2. if ( x === y ) return true;
  3. // if both x and y are null or undefined and exactly the same
  4. if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
  5. // if they are not strictly equal, they both need to be Objects
  6. if ( x.constructor !== y.constructor ) return false;
  7. // they must have the exact same prototype chain, the closest we can do is
  8. // test there constructor.
  9. for ( var p in x ) {
  10. if ( ! x.hasOwnProperty( p ) ) continue;
  11. // other properties were tested using x.constructor === y.constructor
  12. if ( ! y.hasOwnProperty( p ) ) return false;
  13. // allows to compare x[ p ] and y[ p ] when set to undefined
  14. if ( x[ p ] === y[ p ] ) continue;
  15. // if they have the same strict value or identity then they are equal
  16. if ( typeof( x[ p ] ) !== "object" ) return false;
  17. // Numbers, Strings, Functions, Booleans must be strictly equal
  18. if ( ! Object.equals( x[ p ], y[ p ] ) ) return false;
  19. // Objects and Arrays must be tested recursively
  20. }
  21. for ( p in y ) {
  22. if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false;
  23. // allows x[ p ] to be set to undefined
  24. }
  25. return true;
  26. }

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读

    相关 js 对象复制

    深复制:源对象的属性如果有对象,该对象属性修改后,不会引起复制后的对象各属性的改变,源对象的任何属性及子属性,与新对象的没有任何引用关系。 简单来说就一句话,新对象与原对象,