在Javascript中使用===而不是==和typeof的原因是什么? [英] What's the reason to use === instead of == with typeof in Javascript?
问题描述
在许多第三方库和最佳实践博客/推荐等中......通常会看到如下语法:
Throughout many third-party libraries and best practices blogs/recommendations, etc... it is common to see syntax like this:
typeof x === 'object' (instead of typeof x == 'object')
typeof y === 'string' (instead of typeof x == 'string')
typeof z === 'function' (instead of typeof x == 'function')
如果是typeof运算符已经返回一个字符串,还需要键入什么来检查返回值?如果typeof(typeof(x))总是 string ,无论x实际是什么,那么 == 就足够了 === 不必要的。
If the typeof operator already returns a string, what's the need to type check the return value as well? If typeof(typeof(x)) is always string, no matter what x actually is, then == should be sufficient and === unnecessary.
在什么情况下,typeof 不会返回字符串文字?即使有一些边缘情况,为什么附加类型检查用于对象,字符串,函数等...
Under what circumstances will typeof not return a string literal? And even if there's some fringe case why is the additional type check being used for object, string, function, etc...
推荐答案
回答主要问题 - 使用 ==
使用 typeof
没有危险。以下是您可能想要使用 ===
的原因。
To answer the main question - there is no danger in using typeof
with ==
. Below is the reason why you may want to use ===
anyway.
Crockford的建议是在许多情况下使用 ===
会更安全,如果你打算在某些情况下使用它,那么最好是保持一致并将其用于所有事情。
The recommendation from Crockford is that it's safer to use ===
in many circumstances, and that if you're going to use it in some circumstances it's better to be consistent and use it for everything.
您可以考虑是否使用 ==
或 ===
每次检查平等,或者你可以养成总是写 ===
。
The thinking is that you can either think about whether to use ==
or ===
every time you check for equality, or you can just get into the habit of always writing ===
.
几乎没有理由使用 ==
而不是 ===
- 如果您要比较 true
或 false
并且您想要强制(例如您想 0
或''
评估为 false
)然后只需使用 if(!empty_str)
而不是 if(empty_str == false)
。
There's hardly ever a reason for using ==
over ===
- if you're comparing to true
or false
and you want coercion (for example you want 0
or ''
to evaluate to false
) then just use if(! empty_str)
rather than if(empty_str == false)
.
对那些不了解问题的人 ==
在typeof上下文之外,请参阅好的零件:
To those who don't understand the problems of ==
outside of the context of typeof, see this, from The Good Parts:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
这篇关于在Javascript中使用===而不是==和typeof的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!