推荐答案
在 JavaScript 中,假值 (Falsy) 是指在布尔上下文中被视为 false 的值。常见的假值包括:
false0""(空字符串)nullundefinedNaN
真值 (Truthy) 则是指在布尔上下文中被视为 true 的值。除了上述假值之外的所有值都是真值,包括:
true- 非零数字(如
1,-1,3.14) - 非空字符串(如
"hello","0","false") - 对象(如
{},[],new Date()) - 函数
本题详细解读
假值 (Falsy)
假值是指在布尔上下文中会被自动转换为 false 的值。JavaScript 中的假值包括:
false:布尔值false本身就是一个假值。0:数字0是假值,但其他数字(包括负数)都是真值。"":空字符串是假值,但任何非空字符串(包括"0"或"false")都是真值。null:表示空值或未定义的对象。undefined:表示未定义的值。NaN:表示“非数字”(Not-a-Number),通常出现在无效的数学运算中。
真值 (Truthy)
真值是指在布尔上下文中会被自动转换为 true 的值。除了上述假值之外的所有值都是真值,包括:
true:布尔值true本身就是一个真值。- 非零数字:任何非零数字(包括负数和小数)都是真值。
- 非空字符串:任何包含字符的字符串(包括
"0"或"false")都是真值。 - 对象:所有对象(包括空对象
{}和空数组[])都是真值。 - 函数:所有函数都是真值。
示例
// www.javascriptcn.com code example
if (false) {
console.log("This will not run");
}
if (0) {
console.log("This will not run");
}
if ("") {
console.log("This will not run");
}
if (null) {
console.log("This will not run");
}
if (undefined) {
console.log("This will not run");
}
if (NaN) {
console.log("This will not run");
}
if (true) {
console.log("This will run");
}
if (1) {
console.log("This will run");
}
if ("hello") {
console.log("This will run");
}
if ({}) {
console.log("This will run");
}
if ([]) {
console.log("This will run");
}
if (function() {}) {
console.log("This will run");
}在上面的代码中,只有假值对应的 if 语句不会执行,而真值对应的 if 语句会执行。