本文已参与「新人创作礼」活动,一起开启掘金创作之路
In JavaScript, a truthy value is a value that is considered
truewhen encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy exceptfalse,0,-0,0n,"",null,undefined, andNaN.JavaScript uses type coercion in Boolean contexts. truthy 即当数据类型自动转换(或隐式转换)为 Boolean 类型为 true 的值。truthy值比较多,所以可以这样记,除了值是 falsy,其他都是 truthy。值为 falsy 的有
false,0,-0,0n,"",null,undefined, andNaN
truthy values 例子
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
falsy values 例子
if (false)
if (null)
if (undefined)
if (0)
if (-0)
if (0n)
if (NaN)
if ("")
所有 falsy values 解释
| Value | Description |
|---|---|
false | The keyword false. |
0 | The Number zero (so, also 0.0, etc., and 0x0). |
-0 | The Number negative zero (so, also -0.0, etc., and -0x0). |
0n | The BigInt zero (so, also 0x0n). Note that there is no BigInt negative zero — the negation of 0n is 0n. |
"", '', `` | Empty string value. |
| null | null — the absence of any value. |
| undefined | undefined — the primitive value. |
| NaN | NaN — not a number. |
document.all | Objects are falsy if and only if they have the [[IsHTMLDDA]] internal slot.That slot only exists in document.all and cannot be set using JavaScript. |