[英]checking for undefined in javascript— should I use typeof or not?
I'm a bit confused about how best to check if a variable is undefined or not in javascript. 关于如何在javascript中检查变量是否未定义,我有点困惑。 I've been doing it like this: 我一直在这样做:
myVar === undefined;
But is it better in all cases to use typeof instead? 但是在所有情况下使用typeof更好吗?
typeof myVar === undefined;
And what about the use of undefined
vs "undefined"
, which I've also seen? 使用undefined
vs "undefined"
怎么样,我也看到了?
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: 这没关系,但是如果有人无意中覆盖了全局undefined
值,它可能会失败:
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. 必须要说ECMAScript 5指定undefined
是只读的,因此在任何符合的浏览器中,上述内容始终是安全的。
This will never work because it ends up comparing "undefined" === undefined
(different types): 这将永远不会有效,因为它最终比较"undefined" === undefined
(不同类型):
typeof myVar === undefined;
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: 由于undefined
的值可以更改,因此这些测试并不总是可靠的:
a = {}
a.b === undefined
In those cases you could test against void 0
instead: 在这些情况下,您可以测试void 0
:
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. 您可以通过对window.a
进行测试来解决这个问题,但应该首选第一种方法。
我相信在最常见的情况下,例如在检查参数是否通过函数传递时, myVar === undefined
就足够了,因为myVar将始终声明为参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.