Ara*_*hor 74 javascript boolean-expression
我有一个变量.我们称之为toto.
这toto可以设置为undefined,, null字符串或对象.
我想要最简洁的方法来检查是否toto设置为数据,这意味着设置为字符串或对象,既不是undefined也不是null,并在另一个变量中设置相应的布尔值.
我想到了语法!!,看起来像这样:
var tata = !!toto; // tata would be set to true or false, whatever toto is.
Run Code Online (Sandbox Code Playgroud)
第一个!将被设置为false如TOTO的undefined还是null和true别人,和第二个会倒转.
但它看起来有点令人毛骨悚然......所以有更好/更清洁的方法吗?
我已经看过这个问题了,但我想在变量中设置一个值,而不只是在if语句中检查它.
Rob*_*bok 123
是的,你可以随时使用:
var tata = Boolean(toto);
Run Code Online (Sandbox Code Playgroud)
以下是一些测试:
for (var value of [0, 1, -1, "0", "1", "cat", true, false, undefined, null]) {
console.log(`Boolean(${typeof value} ${value}) is ${Boolean(value)}`);
}
Run Code Online (Sandbox Code Playgroud)
结果:
Boolean(number 0) is false
Boolean(number 1) is true
Boolean(number -1) is true
Boolean(string 0) is true
Boolean(string 1) is true
Boolean(string cat) is true
Boolean(boolean true) is true
Boolean(boolean false) is false
Boolean(undefined undefined) is false
Boolean(object null) is false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73365 次 |
| 最近记录: |