我已经试过:angular.isUndefined(value)和not!(value)之间的区别是什么?
if(angular.isUndefined(value)){
// something
}
和
if(!(value)){
// something
}
- 有没有两者之间的区别吗?
- 是否有一个用例来选择一个,而不是其他?
我已经试过:angular.isUndefined(value)和not!(value)之间的区别是什么?
if(angular.isUndefined(value)){
// something
}
和
if(!(value)){
// something
}
!在JavaScript中逻辑非运算符,而angular.isUndefined(值)检查是否参考未定义
使用哪一个,完全取决于你正在尝试在做到底。
见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators和https://docs.angularjs.org/api/ng/function/angular.isUndefined
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:
正如评论所说,当我写“评估为假”有false
null
undefined
NaN
""
(空字符串)和0
包括
正确的。还有其他的东西被强制为假,就像null。 – 2016-10-25 17:47:12