比较对象数组,最佳方式
我有两个数组.在每个数组中,我都有具有很多属性但没有方法的对象.我需要查看数组 1 是否与数组 2 相等.
I have two arrays. In each array I have objects with lots of properties but no methods. I need to see if array 1 is equal with array 2.
一种方法是创建一个函数,该函数传递数组的每个元素,并将对象的每个属性与第二个数组中相似位置的对象进行比较.
One way to do that would be to create a function that pass through each element of an array and compare each property of the object with the object in the similar position in the second array.
问题是数组非常大,而且每个对象都有很多属性.如果还有其他方法,我正在徘徊.例如,在 C++ 中我可以读取内存......但我不知道如何在 js 中做到这一点.
The problem is that the arrays are quite big and also each object has lots of properties. I was wandering if there could be another way. In C++ for example I could read memory... but I don't know how to do that in js.
我需要获得最佳方式,因为这是经常使用的功能的一部分.
I need to obtain the most optimal way since this is part of a function that is used often.
推荐答案
除非它们是同一个数组实例,否则比较内存位置在 JavaScript 中不起作用(当你这样做 arr1 == arr2代码>).
Unless they are the same array instance, comparing the memory locations won't work in JavaScript (what happens when you do arr1 == arr2
).
您需要显式循环.
有些人使用 JSON.stringify()
(注意 pimvdb 评论中解释的问题) 在两个数组上进行比较,并将生成的字符串与 cheat 进行比较,但序列化为字符串并比较声音对我来说非常昂贵.但是它可以工作,所以如果没有性能问题,那就发疯吧!:)
Some people use JSON.stringify()
(watch out for the gotcha explained in the comments by pimvdb) on both arrays and compare the resulting strings to cheat, but serialising to a string and comparing sounds over fully expensive to me. However it works, so if there is no performance problem, go nuts! :)
你也可以试试toSource()
.
我会建立自己的比较函数,该比较函数刚好能满足我的相同的想法.
I would build my own comparative function that compares just enough that satisfies my idea of identical.
相关文章