为什么不使用等式检查数组 [英] Why doesn't equality check work with arrays

查看:90
本文介绍了为什么不使用等式检查数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始时:

"1:2".split(':') == ["1","2"]; 
// false

然后尝试:

[1,2] == [1,2];
// false

最终:

[] == []; 
// false

我发现:

"1:2".split(':').toString() == [1,2].toString();
// true

所以我已经解决了我的初始问题(有点)但是为什么不能相互匹配的数组?

So I've solved my initial issue (kind of) but why can't arrays match each other?

推荐答案

Javascript数组是对象,你不能简单地使用相等运算符 == 了解这些对象的内容是否相同。等于运算符只会测试两个对象实际上是否完全相同(例如 myObjVariable == myObjVariable ,适用于 null undefined 。)

Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same. The equality operator will only test if two object are actually exactly the same instance (e.g. myObjVariable==myObjVariable, works for null and undefined too).

如果你需要检查两个数组是否相等我会建议只是遍历两个数组并验证所有元素具有相同的值(并且两个数组具有相同的长度)。

If you need to check if two array are equals i'd recommend to just traverse both arrays and verify that all the elements have the same value (and that the two array have the same length).

关于自定义对象的相等性我将构建一个具体的等于函数,我将它添加到你的类的原型中。

Regarding custom objects equality i'd build instead a specific equals function and i'd add it to the prototype of your class.

考虑到最后你将两个数组转换为 String 并测试结果字符串的相等性,有一天你可以考虑使用类似但更通用的技术,你会发现在很多地方描述的:

Considering that in the end you converted both arrays to a String and tested equality of the resulting strings, you could one day consider using a similar but more generic technique you'll find described in more than a few places:

JSON.stringify(OBJ1) === JSON.stringify(OBJ2) 

好吧,不要

虽然这是如果属性的顺序对于那些对象实例总是相同的,那么s可以工作,这使得可以很难追踪的非常讨厌的错误的大门敞开。总是喜欢更明确的方法,只需编写一个干净且可读的函数来测试检查所有必需字段的相等性。

While this could work if the order of the properties will always the same for those object instances, this leaves the door open for extremely nasty bugs that could be hard to track down. Always favor a more explicit approach and just write a clean and readable function that will test for equality checking all the required fields.

这篇关于为什么不使用等式检查数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆