比较对象的数组,最佳方式 [英] Compare arrays of objects, optimal way
问题描述
我有两个数组。在每个阵列我有很多的属性,但没有方法的对象。
我要看看是否阵列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 ),并比较两者的字符串的作弊的,但是连载为字符串,然后在比较昂贵的完全的声音给我。然而,它的工作原理,因此,如果没有性能问题,请赶快行动吧! :)
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.
这篇关于比较对象的数组,最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!