typeof!==“undefined” vs.!= null [英] typeof !== "undefined" vs. != null
问题描述
我经常看到JavaScript代码检查未定义的参数等,这样:
I often see JavaScript code which checks for undefined parameters etc. this way:
if (typeof input !== "undefined") {
// do stuff
}
浪费,因为它涉及类型查找和字符串比较,更不用说它的冗长。它是需要的,因为'未定义'可以重命名,但。我的问题是:该代码如何比这种方法更好:
This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because 'undefined' could be renamed, though. My question is: How is that code any better than this approach:
if (null != input) {
// do stuff
}
据我所知, ,所以它不会意外打破。并且,因为!=运算符的类型强制,这将检查未定义和null ...这通常是你想要的(例如对于可选的函数参数)。然而这种形式似乎并不普遍,甚至会导致JSLint向你大喊你使用evil!=运算符。为什么这被认为是不好的风格?
As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (e.g. for optional function parameters). Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator. Why is this considered bad style?
推荐答案
typeof
从来没有被宣布过。所以在这方面更安全:
typeof
allows the identifier to never have been declared before. So it's safer in that regard:
if(typeof neverDeclared == "undefined") //no errors
if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
这篇关于typeof!==“undefined” vs.!= null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!