我经常看到JavaScript代码以这种方式检查未定义的参数等:
if (typeof input !== "undefined") {
// do stuff
}
这似乎有点浪费,因为它涉及类型查找和字符串比较,更不用说它的冗长了。这是必需的,因为undefined
可以重命名。
我的问题是:
与该方法相比,该代码有何优势:
if (null != input) {
// do stuff
}
据我所知,您无法重新定义null
,因此不会意外中断。并且,由于!=
运算符的类型强制,这将同时检查undefined
和null
...,这通常正是您想要的(例如,用于可选功能参数)。
但是,这种形式似乎并不广泛,甚至会导致JSLint对使用邪恶!=
运算符的人大吼大叫。
为什么认为这种风格不好?
works just fine. It is of course not a
null
comparison, but I usually find that if I need to distinguish betweenundefined
andnull
, I actually rather need to distinguish betweenundefined
and just any false value, sodoes it.
If a program redefines
undefined
it is really braindead anyway.The only reason I can think of was for IE4 compatibility, it did not understand the
undefined
keyword (which is not actually a keyword, unfortunately), but of course values could beundefined
, so you had to have this:and the comparison above would work just fine.
In your second example, you probably need double parentheses to make lint happy?