Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - typeof!==“undefined”vs.!= null(typeof !== “undefined” vs. != null)

I often see JavaScript code which checks for undefined parameters etc. this way:

(我经常看到JavaScript代码检查未定义的参数等,这样:)

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.

(这是必要的,因为'undefined'可以重命名。)

My question is: How is that code any better than this approach:

(我的问题是:代码如何比这种方法更好:)

if (null != input) {
    // do stuff
}

As far as I know, you can't redefine null, so it's not going to break unexpectedly.

(据我所知,你不能重新定义null,所以它不会意外地破坏。)

And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (eg for optional function parameters).

(并且,由于!=运算符的类型强制,这将检查undefined和null ...这通常正是您想要的(例如,对于可选的函数参数)。)

Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator.

(然而,这种形式似乎并不普遍,它甚至会导致JSLint对你使用邪恶!=运算符大喊大叫。)

Why is this considered bad style?

(为什么这被认为是不好的风格?)

  ask by Derek Thurn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

typeof is safer as it allows the identifier to never have been declared before:

(typeof更安全,因为它允许标识符从未在之前声明:)

if(typeof neverDeclared === "undefined") // no errors

if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...