我有一个变量。叫它toto
。
这toto
可以设置为undefined
,null
,字符串,或一个对象。
我想检查是否toto
设置为数据,这意味着设置为字符串或对象,也undefined
没有null
设置为,并在另一个变量中设置相应的布尔值。
我想到了语法!!
,看起来像这样:
var tata = !!toto; // tata would be set to true or false, whatever toto is.
第一个!
将被设置为false
如TOTO的undefined
还是null
和true
别人,和第二个会倒转。
但是看起来有点奇怪。那么有没有更清晰的方法可以做到这一点?
我已经看过这个问题,但是我想在变量中设置一个值,而不仅仅是在if
语句中检查它。
是的,您可以随时使用:
var tata = Boolean(toto);
这是一些测试:
for (var value of [0, 1, -1, "0", "1", "cat", true, false, undefined, null]) {
console.log(`Boolean(${typeof value} ${value}) is ${Boolean(value)}`);
}
结果:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句