我想检查变量是否有定义。例如,下面的代码会抛出一个未定义的错误

alert( x );

我如何捕捉这个错误?


当前回答

从技术上讲,正确的解决方案是(我认为):

typeof x === "undefined"

你有时会偷懒,使用

x == null

但是这允许一个未定义的变量x和一个包含null的变量x返回true。

其他回答

我经常这样做:

function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}

一个更简单、更简洁的版本是:

if (!x) {
   //Undefined
}

OR

if (typeof x !== "undefined") {
    //Do something since x is defined.
}

另一个潜在的“解决方案”是使用window对象。它避免了在浏览器中出现引用错误问题。

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}

公认的答案是正确的。只是想多一个选择。你也可以用try…Catch块来处理这种情况。举个奇怪的例子:

var a;
try {
    a = b + 1;  // throws ReferenceError if b is not defined
} 
catch (e) {
    a = 1;      // apply some default behavior in case of error
}
finally {
    a = a || 0; // normalize the result in any case
}

注意catch块,它有点混乱,因为它创建了块级作用域。当然,为了回答问题,这个例子非常简单,它不包括错误处理的最佳实践;)

从技术上讲,正确的解决方案是(我认为):

typeof x === "undefined"

你有时会偷懒,使用

x == null

但是这允许一个未定义的变量x和一个包含null的变量x返回true。