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

alert( x );

我如何捕捉这个错误?


当前回答

我经常这样做:

function doSomething(variable)
{
    var undef;

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

其他回答

void操作符对于传递给它的任何参数/表达式都返回undefined。因此,您可以根据结果进行测试(实际上,一些微型程序将代码从undefined更改为void 0以节省几个字符)

例如:

void 0
// undefined

if (variable === void 0) {
    // variable is undefined
}

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

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

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

typeof x === "undefined"

你有时会偷懒,使用

x == null

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

你也可以使用三元条件运算符:

Var a = "hallo world"; Var a = !a ?文档。写(“我不知道‘a’”):文档。写("a = " + a);

//var a = "hallo world"; Var a = !a ?文档。写(“我不知道‘a’”):文档。写("a = " + a);

我经常这样做:

function doSomething(variable)
{
    var undef;

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