我有一个变量。我们称之为toto
。
此toto
可以设置为undefined
,null
,字符串或对象。
我想用最干净的方法检查toto
是否设置为数据,这意味着设置为字符串或对象,undefined
和null
都没有设置,并设置相应的另一个变量中的布尔值。
我想到了语法!!
,它看起来像这样:
var tata = !!toto; // tata would be set to true or false, whatever toto is.
如果toto为!
或false
且undefined
为其他,则第一个null
将设置为true
,第二个if
会将其反转。< / p>
但它看起来有点令人毛骨悚然......那么有更好/更清洁的方法吗?
我已经看了this question,但我想在变量中设置一个值,而不只是在 output = subprocess.check_output(['kmersFreq', 'sequence.fasta', '2', '0'])
print output
语句中检查它。
答案 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)
或!!obj
将truthy/falsy
转换为true/false
。
var obj = {a: 1}
var to_bool_way1 = Boolean(obj) // true
var to_bool_way2 = !!obj // true