checking for undefined in javascript— should I use typeof or not?

▼魔方 西西 提交于 2019-12-23 07:49:59

问题


I'm a bit confused about how best to check if a variable is undefined or not in javascript. I've been doing it like this:

myVar === undefined;

But is it better in all cases to use typeof instead?

typeof myVar === undefined;

And what about the use of undefined vs "undefined", which I've also seen?


回答1:


This is the best way to check -- totally foolproof:

typeof myVar === "undefined"

This is OK, but it could fail if someone unhelpfully overwrote the global undefined value:

myVar === undefined;

It has to be said that ECMAScript 5 specifies that undefined is read-only, so the above will always be safe in any browser that conforms.

This will never work because it ends up comparing "undefined" === undefined (different types):

typeof myVar === undefined;



回答2:


This test would always work as expected:

typeof a === 'undefined'

Since the value of undefined can be changed, tests like these aren't always reliable:

a = {}
a.b === undefined

In those cases you could test against void 0 instead:

a.b === void 0
// true

However, this won't work for single variable tests:

a === void 0 // <-- error: cannot find 'a'

You could work around that by testing against window.a, but the first method should be preferred.




回答3:


I believe that in the most common cases, e.g. when checking if a parameter is passed through a function, myVar === undefined is enough, as myVar will be always declared as a parameter



来源:https://stackoverflow.com/questions/15093930/checking-for-undefined-in-javascript-should-i-use-typeof-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!