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

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

我有一个变量。我们称它为 toto.

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

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

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

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

如果 toto 为 undefinednull,则第一个 ! 将设置为 false,否则为 true,第二个会将其反转.

但看起来有点奇怪。那么有没有更清晰的方法来做到这一点?

我已经看过 this question,但我想在变量中设置一个值,而不仅仅是在 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) 的 shorthand,并且工作方式完全相同。 (用于将 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`

注意