使用 jQuery 比较两个 Javascript 对象数组

问题描述:

我有两个 JavaScript 对象数组,我想比较它们是否相同.对象可能不会(并且很可能不会)在每个数组中的顺序相同.每个数组不应超过 10 个对象.我认为 jQuery 可能对这个问题有一个优雅的解决方案,但我在网上找不到太多.

I have two arrays of JavaScript Objects that I'd like to compare to see if they are the same. The objects may not (and most likely will not) be in the same order in each array. Each array shouldn't have any more than 10 objects. I thought jQuery might have an elegant solution to this problem, but I wasn't able to find much online.

我知道一个粗暴的嵌套 $.each(array, function(){}) 解决方案可以工作,但是有没有我不知道的内置函数?

I know that a brute nested $.each(array, function(){}) solution could work, but is there any built in function that I'm not aware of?

谢谢.

有一个简单的方法...

There is an easy way...

$(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0

如果以上返回true,则即使元素的顺序不同,两个数组也是相同的.

If the above returns true, both the arrays are same even if the elements are in different order.

注意:这仅适用于 jquery 版本 <3.0.0 使用 JSON 对象时

NOTE: This works only for jquery versions < 3.0.0 when using JSON objects