且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较 JavaScript 中的对象数组

更新时间:2022-04-12 09:09:14

您不能在 JavaScript 解释器的当前常见的基于浏览器的实现中重载运算符.

You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.

要回答最初的问题,您可以通过一种方法来做到这一点,请注意,这有点像黑客,只需 将两个数组序列化为 JSON,然后比较两个 JSON 字符串.这只会告诉您数组是否不同,显然您也可以对数组中的每个 对象执行此操作,以查看哪些对象不同.

To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.

另一个选择是使用一个库,它有一些很好的工具来比较对象 - 我使用并推荐 MochiKit.

Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.

kamens 给出的答案a> 也值得考虑,因为用于比较两个给定对象的单个函数将比执行我建议的任何库都要小得多(尽管我的建议肯定会工作得很好).

The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).

这是一个简单的实现,可能对您来说已经足够了 - 请注意此实现存在潜在问题:

Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:

function objectsAreSame(x, y) {
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName]) {
         objectsAreSame = false;
         break;
      }
   }
   return objectsAreSame;
}

假设两个对象具有完全相同的属性列表.

The assumption is that both objects have the same exact list of properties.

哦,很明显,无论好坏,我都属于只有一个回球点的阵营.:)

Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)