Javascript 检查未定义的值

Javascript 检查未定义的值,javascript,Javascript,我们可以使用以下方法检查变量a是否未定义: if(typeof(a)!=="undefined"){ console.log("a is not undefined"); } 但下面的简单检查能否达到同样的目的 if(!a){ console.log("a is not undefined"); } 因为记住这些东西在Js中是未定义的,null,0,所有这些都是一个对象 这也是为什么我们在如此关心这些事情的情况下面临这个问题 这取决于当时是否声明了a(通过使用var或作为函数中的

我们可以使用以下方法检查变量
a
是否未定义:

if(typeof(a)!=="undefined"){
   console.log("a is not undefined");
}
但下面的简单检查能否达到同样的目的

if(!a){
   console.log("a is not undefined");
}
因为记住这些东西在Js中是未定义的,null,0,所有这些都是一个对象
这也是为什么我们在如此关心这些事情的情况下面临这个问题

这取决于当时是否声明了
a
(通过使用
var
或作为函数中的参数),您可以不使用
typeof

//this produces a log
testOptParam();
//note that the following will have the same result
testOptParam(0);
//but this won't produce log
testOptParam("text...");

function testOptParam(optionalParam){
   if(!optionalParam){
      console.log("optionalParam IS undefined...or null or false or 0");
   }
}
…但如代码中所述,如果变量为(未定义但也为null或等于false或0或“”),则行为相同

此外,如果尚未声明变量,代码可能会引发异常


这就是为什么如果要特别检查某个值是否未定义,就要使用
typeof
解决方案

如果未在任何地方定义
a
,则第二种情况将引发错误。@RayonDabren在这两种情况下,如果未声明
a
,则会出现异常。@NinaScholz,我不同意。。。有什么可以支持你的说法吗?@RayonDabre他们在谈论引用错误。操作时不带括号。
//this produces a log
testOptParam();
//note that the following will have the same result
testOptParam(0);
//but this won't produce log
testOptParam("text...");

function testOptParam(optionalParam){
   if(!optionalParam){
      console.log("optionalParam IS undefined...or null or false or 0");
   }
}