js truthy 和 falsy 究竟是什么

286 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false0-00n""nullundefined, and NaN.

JavaScript uses type coercion in Boolean contexts. truthy 即当数据类型自动转换(或隐式转换)为 Boolean 类型为 true 的值。truthy值比较多,所以可以这样记,除了值是 falsy,其他都是 truthy。值为 falsy 的有 false0-00n""nullundefined, and NaN

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 解释

ValueDescription
falseThe keyword false.
0The Number zero (so, also 0.0, etc., and 0x0).
-0The Number negative zero (so, also -0.0, etc., and -0x0).
0nThe BigInt zero (so, also 0x0n). Note that there is no BigInt negative zero — the negation of 0n is 0n.
""''``Empty string value.
nullnull — the absence of any value.
undefinedundefined — the primitive value.
NaNNaN — not a number.
document.allObjects 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.