JavaScript ==什么时候比===更有意义? [英] When would JavaScript == make more sense than ===?
问题描述
由于在JavaScript比较中应使用哪个equals运算符(== vs ===)?表示它们基本上相同,除了' ===
'还可以确保类型相等,因此' ==
'可以执行类型转换。在道格拉斯·克罗克福德(Douglas Crockford)的 JavaScript:The Good Parts 中,建议始终避免使用 ==
。但是,我想知道设计两组相等运算符的最初想法是什么。
As Which equals operator (== vs ===) should be used in JavaScript comparisons? indicates they are basically identical except '===
' also ensures type equality and hence '==
' might perform type conversion. In Douglas Crockford's JavaScript: The Good Parts, it is advised to always avoid '==
'. However, I'm wondering what the original thought of designing two set of equality operators was.
您是否看到过使用' ==
'实际上比使用' ===
'更合适?
Have you seen any situation that using '==
' actually is more suitable than using '===
'?
推荐答案
比较数字或字符串时应考虑以下情况:
Consider a situation when you compare numbers or strings:
if (4 === 4)
{
// true
}
但是
if (4 == "4")
{
// true
}
和
if (4 === "4")
{
// false
}
这适用于对象以及数组。
This applies to objects as well as arrays.
因此在上述情况下,您必须明智地选择使用==还是== =
So in above cases, you have to make sensible choice whether to use == or ===
这篇关于JavaScript ==什么时候比===更有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!