这种类型可以用“object”进行检查吗?有待改进吗?
if (typeof a !== "object" && typeof b !== "object") {
return a == b;
}
... // check pairwise equality of object a & b using `for in`
相同
if (typeof a !== "object") {
return a == b;
}
它是否与是否有任何带有 typeof b === "object"
的 b
会改变语义
?有什么我应该注意的可怕的边缘情况吗?具有非直观布尔相等或不相等的对象
和本机类型
之间的比较?包括浏览器中的任何错误(我指的是 IE6!)
if (typeof a !== "object" && typeof b !== "object") {
return a == b;
}
... // check pairwise equality of object a & b using `for in`
Is it the same as
if (typeof a !== "object") {
return a == b;
}
Is there any b
with typeof b === "object"
which would change the semantics?
Are there any horrible edge cases I should be aware of? Comparisons between an object
and a native type
which have a non-intuitive boolean equality or disequality? Including any bugs in browser (I mean you IE6!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第二个检查与第一个检查不太一样,不,只是因为 JavaScript 是弱类型的,所以至少要考虑“
.toString()
效果”,如下以及其他人。例如,这些将在第一次检查中失败,但在第二次检查中通过:或者,更简单一点(显示您可能想要考虑的情况......但这通过了两项检查):
一个解决方法是执行一个值 并使用
===
进行类型检查 which是一个严格的比较运算符,您也会进行类型检查...但我不完全确定这就是您所追求的,因为当前检查明确“不是对象” ”。The second check is not quite the same as the first, no, simply because JavaScript is weakly typed so at the very least consider the "
.toString()
effect", as well as others. For example these would fail the first check, but pass in the second:Or, a bit simpler (showing a case you may want to consider...but this passes both checks):
One fix would be to do a value and type check with
===
which is a strict comparison operator, you get type checking as well...but I'm not entirely sure that's what you're after, since the current check is explicitly "not an object".不一样。
这里有一个例子来理解为什么:
同样的事情也可能发生在数字上:
由于显而易见的原因,你的两个 if 语句并不相同。
您可以使用
instanceof
运算符“改进”类型检查以满足游览需求:it's not the same.
here's an example to understand why :
the same thing can happen for numbers :
your two if statements are not the same for the obvious reason.
you could "improve" your type check by using the
instanceof
operator to suite tour needs :看看 isEqual 来自 Underscore.js。它“在两个对象之间执行优化的深度比较,以确定它们是否应该被视为相等。”它适用于所有类型的变量。这是它的实现方式:
请参阅 Underscore.js 源代码 以查看其余部分这个函数使用的函数。
很容易错过一些边缘情况,因此我建议使用像这样经过良好测试的代码,而不是重新发明轮子。
Take a look at isEqual from Underscore.js. It "Performs an optimized deep comparison between the two objects, to determine if they should be considered equal." It works for all types of variables. This is how it's implemented:
See the Underscore.js source code to see the rest of the functions used by this one.
It's easy to miss some edge cases so I would recommend using a well tested code like this one instead of reinventing the wheel.