gpt4 book ai didi

javascript - 将 truthy 或 falsy 转换为显式 bool 值,即转换为 True 或 False

转载 作者:IT王子 更新时间:2023-10-29 02:50:34 26 4
gpt4 key购买 nike

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

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

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

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

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

如果 toto 是 undefinednulltrue,第一个 ! 将被设置为 false 否则,第二个会反转它。

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

我已经看过 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

关于javascript - 将 truthy 或 falsy 转换为显式 bool 值,即转换为 True 或 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com