if ("hello") console.log("strings are truthy");
if (42) console.log("nonzero numbers are truthy");
if ([]) console.log("empty arrays are truthy");
if ({}) console.log("empty objects are truthy");
if (!0) console.log("zero is falsy");
if (!"") console.log("empty string is falsy");
const falsyValues = [false, 0, -0, 0n, "", null, undefined, NaN];
for (const v of falsyValues) {
console.log(v, "->", Boolean(v));
}
就这些。列表如下:
false:布尔值本身。
0 和 -0:两个零。
0n:BigInt 零。
"":空字符串(单引号、双引号或反引号都一样)。
null:表示“有意为空”的值。
undefined:表示“尚未设置”的值。
NaN:像 0 / 0 这样的无效运算的结果。
记住这八个。以后遇到拿不准的值,就问自己:“它是这八个之一吗?”如果不是,它就是真值。
意外情况:"0"、[] 和 {}
初学者在这里最容易栽跟头。很多值看起来是空的,其实是真值:
console.log(Boolean("0")); // true - it's a non-empty string
console.log(Boolean("false")); // true - still a non-empty string
console.log(Boolean(" ")); // true - a space counts
console.log(Boolean([])); // true - empty array is an object
console.log(Boolean({})); // true - empty object is an object
console.log(Boolean(new Date()));// true
const items = [];
const user = {};
// Wrong - always runs:
if (items) console.log("items has stuff");
// Right:
if (items.length === 0) console.log("items is empty");
if (Object.keys(user).length === 0) console.log("user has no fields");
字符串也一样,如果你想把只包含空白的字符串视为空:
const input = " ";
if (input) console.log("truthy, but not really useful");
if (input.trim() === "") console.log("actually empty");
console.log("a" && "b"); // "b" - both truthy, returns the last
console.log(0 && "b"); // 0 - short-circuits on the falsy one
console.log("" || "fallback"); // "fallback" - first is falsy, returns the second
console.log("hi" || "fallback");// "hi" - first is truthy, returns it
这就是为什么 value || defaultValue 是设置默认值的常用写法。但它有一个陷阱:它把所有假值一视同仁,包括 0 和 "",而它们常常是有效的输入:
function greet(name) {
const who = name || "stranger";
console.log("Hello, " + who);
}
greet("Ada"); // Hello, Ada
greet(""); // Hello, stranger - but maybe "" was intentional?
greet(0); // Hello, stranger - and 0 might be a valid id