2014-09-02 111 views

回答

2
var foo = false; 


if(!foo) { 
    // will log 
    console.log("foo is defined but false"); 
} 

if(angular.isUndefined(foo)){ 
    // will not log as foo is defined 
    console.log("foo is undefined") 
} 

另一个例子,而不foo定义

if(!foo) { 
    // will throw exception "Uncaught ReferenceError: foo is not defined " 
    console.log("foo is defined but false"); 
} 

if(angular.isUndefined(foo)){ 
    // will log 
    console.log("foo is undefined") 
} 

如此有效angular.isUndefined(富)并没有别的比评估

if(typeof foo == "undefined") 

包裹保存1个字符是的。 !

而 - 运算符检查是否定义的变量的计算结果为假 所以

if(!foo) 

是同样喜欢

if(foo != true) 

UPDATE:

正如评论所说,当我写“评估为假”有falsenullundefinedNaN""(空字符串)和0包括

+0

正确的。还有其他的东西被强制为假,就像null。 – 2016-10-25 17:47:12

相关问题