对“深度相等"进行功能检查.嵌套对象 [英] Function checking for "deep equality" of nested objects

查看:54
本文介绍了对“深度相等"进行功能检查.嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来检查两个对象是否具有相同的值.此功能要求我检查存储为原始对象内的值的所有对象是否相等.我开发的方法(请参见下面的代码)是首先检查非对象值的相等性.然后,如果所有这些都匹配,我将再次遍历这些对象并递归调用原始函数,这使我可以比较两个对象的每个嵌套级别.

I am trying to write a function that checks if two objects have the same values. This function requires that I check for the equality of any objects that are stored as values inside the original objects. The approach I have developed (see code below) is to first check the equality of non-object values. Then, if these all match, I iterate over the objects again and make a recursive call to the original function, which allows me to compare each nested level of the two objects.

但是,这种方法仅部分起作用.递归调用的性质意味着我只能检查对象中第一个键-值对上嵌套对象的相等性.一旦比较了第一套嵌套对象并且递归调用返回,我就无法弄清楚如何检查包含嵌套对象的任何其他键值对.这是函数:

However, this approach only partially works. The nature of the recursive call means I can only check the equality of nested objects at the first key - value pair in the object. I cannot figure out how to check any additional key-value pairs containing nested objects once the first set of nested objects have been compared and the recursive call returns. Here is the function:

var deepEqual = function(val1, val2) {
  if (typeof val1 === 'object' && typeof val2 === 'object') {
      for (i in val1) {
        for (i in val2){
          if (typeof val1[i] !== 'object' && typeof val2[i] !== 'object') {
            if (val1[i] !== val2[i]) {
              return false
            }
          }
        }
      }
      for (i in val1) {
        for (i in val2){
          if (typeof val1[i] === 'object' && typeof val2[i] === 'object') {
            return deepEqual(val1[i], val2[i])
          }
        }
      }
    return true
  }
  else if (val1 === val2) {
    return true
  }
  else return false
}

我的基本问题是,我认为我需要递归调用来检查嵌套对象的深度相等性,但是我只能成功执行一次此检查.有没有人试图解决这样的问题?如果需要更具体的对象,我将提供一些示例结果.谢谢!

My basic problem is that I believe I need a recursive call to check for the deep equality of nested objects, but that I can only do this check once successfully. Has anybody tried to solve a problem like this? I'll provide examples of my results for specific objects if you need more specific. Thanks!

推荐答案

一个简单的解决方案是对对象进行JSON字符串化并比较它们的字符串表示形式.正如@Jan所说的...

A simple solution would be to JSON stringify the objects and compare their string representations. As @Jan mentions ...

这仅在对象以完全相同的方式初始化时才有效 道路.如果属性相同但顺序不同,它将 失败

this will only work if the objects are initialized in the exact same way. If the properties are the same but in a different order, it will fail

...这有点脆弱,但可能适合您的目的.

...this is a bit brittle but may suit your purposes.

这篇关于对“深度相等"进行功能检查.嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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