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

alert( x );

我如何捕捉这个错误?


当前回答

我们可以像下面这样检查undefined

var x; 

if (x === undefined) {
    alert("x is undefined");
} else {
     alert("x is defined");
}

其他回答

我经常这样做:

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.
}

就像下面这样做:

function isNotDefined(value) {
  return typeof value === "undefined";
}

叫它:

isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false

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

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

我经常用最简单的方法:

var variable;
if (variable === undefined){
    console.log('Variable is undefined');
} else {
    console.log('Variable is defined');
}

编辑:

如果没有初始化变量,将抛出异常"Uncaught ReferenceError: variable is not defined…"