我有一个变量。我们就这样称呼它吧toto
.
This toto
可以设置为undefined
, null
、字符串或对象。
我想检查一下是否toto
设置为数据,即设置为字符串或对象,两者都不是undefined
nor null
,并在另一个变量中设置相应的布尔值。
我想到了语法!!
,看起来像这样:
var tata = !!toto; // tata would be set to true or false, whatever toto is.
首先!
将被设置为false
如果托托是undefined
or null
and true
否则,第二个就会颠倒它。
但看起来有点奇怪。那么有没有更清晰的方法来做到这一点呢?
我已经看过了这个问题 https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in,但我想在变量中设置一个值,而不仅仅是在变量中检查它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)}`);
}
Results:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)