检查变量是否设置的最佳方法是什么?

时间:2013-04-16 06:45:01

标签: javascript

在我看来,Javascript有很多奇怪的怪癖。这是其中之一

var a;
!a //true, a is not set
a = null
!a //true, a is not set
a = 1
!a //false, a is set!
a = 0
!a//true, a is not set!

我发现所有这些值都非常合理,除了a = 0的情况,这对我来说是完全错误的。有没有合理的方法来绕过这个问题,而不必向我的代码添加批量?

2 个答案:

答案 0 :(得分:1)

使用typeof

进行检查
if(typeof(a) != "undefined") {
     //code goes here
}

以下是一些相关问题。

How can I check whether a variable is defined in JavaScript?

Test if a variable is defined in javascript?

答案 1 :(得分:0)

if (typeof a !="undefined")
{
 //write your code here
}