我经常看到这样检查未定义参数的JavaScript代码:
if (typeof input !== "undefined") {
// do stuff
}
这看起来很浪费,因为它涉及到一个类型查询和一个字符串比较,更不用说冗长了。这是需要的,因为'未定义'可以被重命名。我的问题是:该代码如何比这种方法更好:
if (null != input) {
// do stuff
}
据我所知,你不能重新定义null,所以它不会意外中断。而且,由于!=运算符的类型强制,这将检查undefined和null ...这通常正是你想要的(例如对于可选的函数参数)。然而,这种形式似乎并不普遍,甚至导致JSLint使用邪恶的!=运算符来大吼你。为什么这被认为是不好的风格?
如果变量被声明(或者用var关键字,作为函数参数,或者作为全局变量),我认为最好的方法是:
if (my_variable === undefined)
jQuery做到了,所以这对我来说已经足够了:-)
否则,你将不得不使用typeof避免一个ReferenceError。
如果你期望undefined被重新定义,你可以像这样包装你的代码:
(function(undefined){
// undefined is now what it's supposed to be
})();
ypeof允许标识符从来没有被声明过。所以在这方面更安全:
if(typeof neverDeclared == "undefined") //no errors
if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined