truthy 和 falsy
JavaScript 里为 falsy 的值:
false
null
undefined
0
和-0
NaN
''
,""
, ``(Empty template string 空模板字符串)document.all
0n
: BigInt
所有的 JS 值非 truthy 即 falsy,所以,除了上述几种 falsy 值,其他的值全部为 truthy.
逻辑操作符 &&
和 ||
&&
和 ||
的操作数可以是任意类型的表达式,返回值并不总是布尔值。
"foo" && "bar"; // "bar"
"bar" && "foo"; // "foo"
"foo" && ""; // ""
"" && "foo"; // ""
33 && true; // true
true && 33; // 33
false && 33; // false
33 && false; // false
33 || true; // 33
true || 33; // true
false || 33; // 33
33 || false; // 33
"foo" || "bar"; // "foo"
"bar" || "foo"; // "bar"
"foo" || ""; // "foo"
"" || "foo"; // "foo"
if
… else
以下的code,如果指定条件为 falsy, 执行 if
相关的语句,反之执行else
相关的语句:
// false,0,undefined, null, "", '', NaN 等等
if (falsy值) {
// 条件为falsy时执行的操作
} else {
// 条件为truthy时执行的操作
}
例 1
let values = [1, 2, 3];
while (values.length) {
console.log(values.pop());
}
例 2
let user = { isAdmin: true };
// ...
if (user && user.isAdmin) {
// ...
}
[1] https://stackoverflow.com/questions/35642809/understanding-javascript-truthy-and-falsy
[2] https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript