Javascript 将真值或假值转换为显式布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31155477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:19:12  来源:igfitidea点击:

Convert truthy or falsy to an explicit boolean

javascriptboolean-expression

提问by Aracthor

I have a variable. Let's call it toto.

我有一个变量。让我们称之为toto

This totocan be set to undefined, null, a string, or an object.

toto可以设置为undefinednull、字符串或对象。

I would like to check if totois set to a data, which means set to a string or an object, and neither undefinednor null, and set corresponding boolean value in another variable.

我想检查是否toto设置为数据,这意味着设置为字符串或对象,并且既不是undefined也不是null,并在另一个变量中设置相应的布尔值。

I thought of the syntax !!, that would look like this:

我想到了语法!!,它看起来像这样:

var tata = !!toto; // tata would be set to true or false, whatever toto is.

The first !would be set to falseif toto is undefinedor nulland trueelse, and the second one would invert it.

第一个!将设置为falseif toto is undefinedor nulland trueelse,第二个将反转它。

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 ifstatement.

我已经看过这个问题,但我想在变量中设置一个值,而不仅仅是在if语句中检查它。

回答by Robo Robok

Yes, you can always use this:

是的,你总是可以使用这个:

var tata = Boolean(toto);

And here are some tests:

这里有一些测试:

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