如何在JavaScript中检查未定义的变量

本文翻译自: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');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值