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

alert( x );

我如何捕捉这个错误?


当前回答

就像下面这样做:

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

叫它:

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

其他回答

这个错误告诉你x根本不存在!它没有被声明,这与被赋值是不同的。

var x; // declaration
x = 2; // assignment

如果你声明了x,就不会出现错误。你会得到一个警告,说未定义,因为x存在/已经声明,但还没有被赋值。

要检查变量是否已声明,您可以使用typeof,任何其他检查变量是否存在的方法都会引发与初始时相同的错误。

if(typeof x  !==  "undefined") {
    alert(x);
}

这是检查存储在x中的值的类型。只有当x尚未声明或已声明且尚未赋值时,它才会返回undefined。

我经常这样做:

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
}

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

typeof x === "undefined"

你有时会偷懒,使用

x == null

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

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

var x; 

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