我想检查变量是否有定义。例如,下面的代码会抛出一个未定义的错误
alert( x );
我如何捕捉这个错误?
我想检查变量是否有定义。例如,下面的代码会抛出一个未定义的错误
alert( x );
我如何捕捉这个错误?
当前回答
我经常用最简单的方法:
var variable;
if (variable === undefined){
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
编辑:
如果没有初始化变量,将抛出异常"Uncaught ReferenceError: variable is not defined…"
其他回答
我经常用最简单的方法:
var variable;
if (variable === undefined){
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
编辑:
如果没有初始化变量,将抛出异常"Uncaught ReferenceError: variable is not defined…"
你也可以使用三元条件运算符:
Var a = "hallo world"; Var a = !a ?文档。写(“我不知道‘a’”):文档。写("a = " + a);
//var a = "hallo world"; Var a = !a ?文档。写(“我不知道‘a’”):文档。写("a = " + a);
就像下面这样做:
function isNotDefined(value) {
return typeof value === "undefined";
}
叫它:
isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false
我们可以像下面这样检查undefined
var x;
if (x === undefined) {
alert("x is undefined");
} else {
alert("x is defined");
}
真正测试变量是否未定义的唯一方法是执行以下操作。记住,undefined是JavaScript中的一个对象。
if (typeof someVar === 'undefined') {
// Your variable is undefined
}
这个线程中的其他一些解决方案会让你相信一个变量是未定义的,即使它已经定义了(例如,值为NULL或0)。