我认为您在寻找的是!!val==false
,可以转换为更短的形式!val
,但含义不变:
您可以看到:
function checkValue(value) {
console.log(!!value);
}
checkValue();
checkValue(null);
checkValue(undefined);
checkValue(false);
checkValue("");
checkValue(true);
checkValue({});
checkValue("any string");
这可以通过使用 !
运算符来翻转值来实现。
例如,如果您想要翻转 null
,可以这样做:
console.log(!null) // that would output --> true
如果你像这样翻转两次:
console.log(!!null) // that would output --> false
和 undefined
或 false
一样。
你的代码:
if(val==null || val===false){
;
}
那么就会变成:
if(!val) {
;
}
即使存在一个字符串但其长度为零,这种方法也适用于所有情况。
现在,如果您希望它也适用于数字0(如果对其进行双重取反,则变为false
),则您的if语句将变为:
if (!variable || (typeof variable === "number" && variable === 0)) {
// code to be executed if variable is undefined, null, "", [], or 0
}
if(!val && val !== 0) {
}
'0'
不等同于false
。 - Felix Klingif (!value)
有什么问题吗? - Timo Ernst