如何确定页面中是否定义了JavaScript变量?

SSh*_*rma 112 javascript

如果在页面中定义变量,我如何检入JavaScript?假设我想检查一个名为"x"的变量是否在页面中定义,如果我这样做if(x != null),它会给我一个错误.

SSh*_*rma 158

我让它使用 if (typeof(x) != "undefined")

  • 我只是在firebug中检查过,undefined确实映射到字符串"undefined",当他们写JS时,有人严重抽烟,我站得更正了. (38认同)
  • @Ben:字符串`"undefined"`更正确 - 如果使用`!==`那么引号是必要的,因为`typeof`会产生一个字符串. (2认同)

And*_*ges 49

为了避免意外分配,我养成了颠倒条件表达式顺序的习惯:

if ('undefined' !== typeof x) {
Run Code Online (Sandbox Code Playgroud)

  • 反向作业我讨厌. (17认同)
  • 尤达有条件 (5认同)
  • 你想使用`!==`,而不是`===`.:) (2认同)
  • 细节,细节!;-) (2认同)
  • .sentences english 那些完全颠倒的 (2认同)

Pab*_*era 22

与其他运算符不同,typeof运算符在与未声明的符号一起使用时不会抛出ReferenceError异常,因此可以安全使用...

if (typeof a != "undefined") {
    a();
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*rdi -5

尝试使用未定义

if (x !== undefined)
Run Code Online (Sandbox Code Playgroud)

这就是检查特定浏览器功能的方式。