本文介绍了在javascript中检查undefined--我应该使用typeof吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何最好地检查javascript中是否未定义变量感到困惑。我一直这样做:

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;

但在所有情况下使用typeof更好吗?

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

typeof myVar === undefined;

那么使用 undefined vs undefined,我也见过?

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

推荐答案

这个是最好的检查方式 - 完全万无一失:

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

typeof myVar === "undefined"

这没关系,但如果有人无意中覆盖全局 undefined ,它可能会失败值:

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

myVar === undefined;

必须说ECMAScript 5指定 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.

这将永远不会有效,因为它最终会比较undefined=== undefined (不同类型):

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

typeof myVar === undefined;

这篇关于在javascript中检查undefined--我应该使用typeof吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 01:59