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 评论中解释的问题) 在两个数组上进行比较,并将生成的字符串与 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.
这篇关于比较对象数组,最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较对象数组,最佳方式
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01