将truthy或falsy转换为显式布尔值,即True或False

Convert truthy or falsy to an explicit boolean, i.e. to True or False

本文关键字:布尔值 True False truthy falsy 转换      更新时间:2023-09-26

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

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

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

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

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

如果toto是undefinednulltrue,则第一个!将被设置为false,而第二个则将其反转

但这看起来有点奇怪。那么,有没有更明确的方法来做到这一点呢?

我已经研究过这个问题,但我想在变量中设置一个值,而不仅仅是在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

!!o也是Boolean(o)的简写,工作原理完全相同。(用于将truthy/falsy转换为true/false)。

let o = {a: 1}
Boolean(o) // true
!!o // true
// !!o is shorthand of Boolean(o) for converting `truthy/falsy` to `true/false`

注意