最简洁的转换为布尔值的方法

时间:2015-07-01 07:48:38

标签: javascript boolean-expression

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

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

我想用最干净的方法检查toto是否设置为数据,这意味着设置为字符串或对象,undefinednull都没有设置,并设置相应的另一个变量中的布尔值。

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

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

如果toto为!falseundefined为其他,则第一个null将设置为true,第二个if会将其反转。< / p>

但它看起来有点令人毛骨悚然......那么有更好/更清洁的方法吗?

我已经看了this question,但我想在变量中设置一个值,而不只是在 output = subprocess.check_output(['kmersFreq', 'sequence.fasta', '2', '0']) print output 语句中检查它。

2 个答案:

答案 0 :(得分:108)

是的,您可以随时使用:

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

答案 1 :(得分:2)

您可以使用Boolean(obj)!!objtruthy/falsy转换为true/false

var obj = {a: 1}
var to_bool_way1 = Boolean(obj) // true
var to_bool_way2 = !!obj // true