将true或falsy转换为一个明确的布尔值,即True或False [英] Convert truthy or falsy to an explicit boolean, i.e. to True or False
问题描述
我有一个变量.我们称之为toto
.
I have a variable. Let's call it toto
.
此toto
可以设置为undefined
,null
,字符串或对象.
This toto
can be set to undefined
, null
, a string, or an object.
我想检查是否将toto
设置为数据,即是否设置为字符串或对象,而不是undefined
或null
,并在另一个变量中设置相应的布尔值.
I would like to check if toto
is set to a data, which means set to a string or an object, and neither undefined
nor null
, and set corresponding boolean value in another variable.
我想到了语法!!
,它看起来像这样:
I thought of the syntax !!
, that would look like this:
var tata = !!toto; // tata would be set to true or false, whatever toto is.
如果toto是undefined
或null
以及true
,则第一个!
将设置为false
,第二个将其反转.
The first !
would be set to false
if toto is undefined
or null
and true
else, and the second one would invert it.
但是看起来有点奇怪.那么,有没有更清晰的方法呢?
But it looks a little bit odd. So is there a clearer way to do this?
I already looked at this question, but I want to set a value in a variable, not just check it in an if
statement.
推荐答案
是的,您始终可以使用以下方法:
Yes, you can always use this:
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
这篇关于将true或falsy转换为一个明确的布尔值,即True或False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!