Javascript: Deep Comparison

本小妞迷上赌 提交于 2019-12-01 17:23:40

"Deep equality", which is what the question you linked to is talking about, and "strict equality" are two different things. "Deep equality" means, as you said, "equal keys and equal values." "Strict equality" for objects means "same instance." Strict equality implies deep equality, but objects can be deeply equal without being strictly equal.

Your code is somewhat inefficient because you only need one loop, but it will behave correctly if you check a === b in an else block and return true after the for loops. This is because you should be handling objects separately from primitive values like strings and numbers. I've removed some logging for the sake of clarity, and I tried to keep your style.

var obj = {here: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1}));
// → false
console.log(deepEqual(obj, {here: 2}));
// → true
console.log(obj === { here:2 });
// → false
function deepEqual(a,b)
{
  if( (typeof a == 'object' && a != null) &&
      (typeof b == 'object' && b != null) )
  {
     var count = [0,0];
     for( var key in a) count[0]++;
     for( var key in b) count[1]++;
     if( count[0]-count[1] != 0) {return false;}
     for( var key in a)
     {
       if(!(key in b) || !deepEqual(a[key],b[key])) {return false;}
     }
     for( var key in b)
     {
       if(!(key in a) || !deepEqual(b[key],a[key])) {return false;}
     }
     return true;
  }
  else
  {
     return a === b;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!