检查值是否为false,true或null

时间:2020-05-30 11:07:22

标签: javascript

我想检查变量是否为false,true或null。如果为null或未定义,则默认情况下将数组分配给变量。在其他语言中,此语法很好用。但是在js中,当value为false时,它将数组分配给myBool

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)

我设法使用这种语法,只检查空值

const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);

在js中还有更好的方法吗?

2 个答案:

答案 0 :(得分:5)

无效合并。

检查变量是否为null或未定义,并在这种情况下将其分配给默认值。 0false不会被认为是空值,并将被分配给该值。

无效的合并运算符??的行为与||运算符非常相似,不同之处在于我们在评估运算符时不使用“真实的”。取而代之的是,我们使用nullish的定义,意思是“值严格等于null还是undefined?”

let a = null;

let b = a ?? "test";

console.log(b);

带有false

的示例

let a = false;

let b = a ?? "test";

console.log(b);

答案 1 :(得分:1)

另一个答案的另一种选择是确保向后兼容(即使IE6也支持),因为它没有使用无效的合并运算符。如果您不使用babel,它会更冗长,但也更方便和易用。 希望对您有帮助!

const boolFromBody = null;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = undefined;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = false;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);