How can I determine if a JavaScript variable is defined in a page?

How can i check in JavaScript if a variable is defined in a page? Suppose I want to check if a variable named "x" is defined in a page, if I do if(x != null), it gives me an error.

97979 次浏览

try to use 未定义

if (x !== undefined)

这就是检查特定浏览器特性的方法。

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

与其他操作符不同,typeof 操作符在与未声明的符号一起使用时不会引发 ReferenceError 异常,因此使用..。

if (typeof a != "undefined") {
a();
}

假设您的函数或变量是在典型的“ global”(参见: < strong > window ’s)范围内定义的,我更喜欢:

if (window.a != null) {
a();
}

or even the following, if you're checking for a function's existence:

if (window.a) a();

为了避免意外赋值,我习惯于颠倒条件表达式的顺序:

if ('undefined' !== typeof x) {

你可以这样做:

如果(window.x! = = 未定义){ //你在这里编码 }

As others have mentioned, the typeof operator can evaluate even an undeclared identifier without throwing an error.

alert (typeof sdgfsdgsd);

将显示“未定义”,类似于

alert (sdgfsdgsd);

将抛出一个参考错误。