本文翻译自:How to check a not-defined variable in JavaScript
I wanted to check whether the variable is defined or not. 我想检查变量是否已定义。 For example, the following throws a not-defined error 例如,以下引发了未定义的错误
alert( x );
How can I catch this error? 我怎么能抓到这个错误?
#1楼
参考:https://stackoom.com/question/3bFd/如何在JavaScript中检查未定义的变量
#2楼
I often use the simplest way: 我经常使用最简单的方法:
var variable;
if (variable === undefined){
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
EDIT: 编辑:
Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..." 在不初始化变量的情况下,将抛出异常“Uncaught ReferenceError:variable not defined not ...”
#3楼
You can also use the ternary conditional-operator: 您还可以使用三元条件运算符:
var a = "hallo world"; var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
//var a = "hallo world"; var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
#4楼
We can check undefined
as follows 我们可以检查undefined
如下
var x;
if (x === undefined) {
alert("x is undefined");
} else {
alert("x is defined");
}
#5楼
The accepted answer is correct. 接受的答案是正确的。 Just wanted to add one more option. 只想添加一个选项。 You also can use try ... catch
block to handle this situation. 您还可以使用try ... catch
块来处理这种情况。 A freaky example: 一个怪异的例子:
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
}
Be aware of catch
block, which is a bit messy, as it creates a block-level scope. 请注意catch
块,这有点乱,因为它创建了块级范围。 And, of course, the example is extremely simplified to answer the asked question, it does not cover best practices in error handling ;). 当然,这个例子非常简化以回答问题,它不包括错误处理的最佳实践;)。
#6楼
Another potential "solution" is to use the window
object. 另一个潜在的“解决方案”是使用window
对象。 It avoids the reference error problem when in a browser. 它避免了在浏览器中引用错误的问题。
if (window.x) {
alert('x exists and is truthy');
} else {
alert('x does not exist, or exists and is falsy');
}