JavaScript深度比较 [英] Javascript Deep Comparison

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

问题描述

有人问过有关对象深度比较的问题,我有解决方法.但是我不完全了解解决方案中的一条线.

Questions about deep comparison of objects have been asked, and I have the solution. But there is a line in the solution that I don't completely understand.

这是解决方案,是雄辩JS的第4章中的一个问题,用于比较对象.我得到了除行外的所有内容:

This is the solution, it is a question in Ch 4 of Eloquent JS to compare objects. I get all of it except the line:

    if (!(prop in a) || !deepEqual(a[prop], b[prop]))

位于底部.这是全部功能:

It is found toward the bottom. Here is full function:

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

if(!(a中的prop)是在该索引处比较'b'中某个属性的存在,还是在比较值?

Is if (!(prop in a) comparing the existence of a property in 'b' at that index, or is it comparing values?

完全相同的q.关于下半部分,但我知道这是一个不同的答案:!deepEqual(a [prop],b [prop])是哪种类型的比较(例如,对还是错)?我理解递归,但是正如我之前的问题一样,这是在进行存在"比较,还是对值中的信息进行比较?

Really the same q. about the second half, but I know it's a different answer: what type of comparison is !deepEqual(a[prop], b[prop]) making (e.g., true or false)? I understand the recursion, but as in my previous question, is this making an 'it exists' comparison, or a comparison of the information in the values?

谢谢.

推荐答案

根据MDN:

如果指定的属性位于指定的对象中,则 in运算符返回 true .

也:

for ... in语句遍历可枚举属性,以任意顺序.对于每个不同的属性,都可以执行语句.

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

为回答您的第一个问题,中的 prop正在检查对象 prop (对象 b 中的字段)> a .

So to answer your first question, prop in a is checking whether prop, a field from object b, exists in object a.

要回答第二个问题, deepEqual(a [prop],b [prop])正在检查对象 a [prop] b [道具] 相等,包括其所有子项和内容.

To answer your second question, deepEqual(a[prop], b[prop]) is checking whether the object a[prop] and b[prop] are equal including all its children and contents.

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

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