![](/img/trans.png)
[英]Checking for Boolean Values in Typescript/Javascript Pertaining to “true”, “false”, and “undefined”
[英]!! sytactic sugar to check undefined in javascript for boolean values
var x = false;
if (!!x) { // syntactic sugar for x ! =undefined
alert('I will not be shown');
}
在这里,x确实具有值“ false”,因此已定义。 这里的问题是检查未定义的正确方法吗?
如果您只想拒绝undefined
则最好使用:
if (typeof x !== "undefined") {
// code
}
因为!!x
会忽略x = false
/ x = ''
类的其他值。 进行真相测试很简单,可以使用:
if (x) { ... }
真的没有意义
if (!!x)
相对于
if (x)
作为由!
执行的布尔转换 无论如何, if
语句将完全相同。
!!
当您想强制进行布尔转换并保留结果时,“技巧”很有用:
var xIsTruthy = !!x;
之后,变量xIsTruthy
将包含true
或false
。
当然,
if (x)
如果x
是undefined
, null
, 0
, ""
, false
或NaN
以外的其他null
,则将成功。 有时这样就可以了,因为您知道x
应该是什么,例如什么都不是或对象引用。 但是,如果您需要更具体的测试,则必须明确编写该测试。
undefined
(或undefined
,这就是您要检查的)最广泛使用的检查可能是:
if (typeof x !== "undefined") {
console.log("x is defined");
}
正如(我认为)您已经注意到的那样,对于任何虚假的东西,换句话说,对于null
, undefined
, 0
, ""
, false
和NaN
,您的测试都会产生一个true
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.