深度比较JavaScript函数 [英] Deep Compare JavaScript function

查看:49
本文介绍了深度比较JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Eloquent JavaScript的第三版,尽管我在SO上看到了一个或两个不同的答案,这些答案似乎在执行逻辑上几乎完全相同,但无论我如何工作,我的工作似乎都没有它.

I'm working my way through the 3rd edition of Eloquent JavaScript and although I've seen one or two various answers on SO that seem almost identical in execution logic to mine that work mine just doesnt seem to no matter how I tweek it.

目标:创建一个深层比较功能,可以比较两个对象,并根据它们的属性确定它们是否是相同对象类型(相同的键和值)的不同实例,而与引用无关...

THE GOAL: create a deep comparison function that can compare two objects and determine based on their properties if theyre different instances of the same type of object (same keys and values) regardless of reference...

任何人都可以在我的代码中发现该错误吗?

Can anyone spot the bug in my code?

function deepEqual(a,b){
  if((typeof a=='object'&& a!=null)&&(typeof b=='object'&& b!=null)){
   if(Object.keys(a).length != Object.keys(b).length){return false}    
    for(let key in a){
        if(a[key]==b[key]){
          if(!deepEqual(a[key],b[key])){return false}
        }else{
          return false
        }
    }
   return true
  }else if(a!==b){return false}

  else{return true}
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true (reads true currently)
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false (reads false currently)
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true (reads false currently)

推荐答案

错误在这里:

if (a[key] == b[key])

如果它们是对象,那么即使它们相等",条件也可能返回false.

if they're objects the condition may return false even if they're "equal".

function deepEqual(a, b) {
  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (Object.keys(a).length != Object.keys(b).length) return false;
    for (var key in a) if (!deepEqual(a[key], b[key])) return false;
    return true;
  } else return a === b
}

var obj = {here: {is: "an"}, object: [2]};
console.log(deepEqual(obj, obj));
// → true 
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false 
console.log(deepEqual(obj, {here: {is: "an"}, object: [2]}));
// → true 

这篇关于深度比较JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆