JavaScript 中的所有错误值 [英] All falsey values in JavaScript
问题描述
JavaScript 中哪些值是falsey",这意味着它们在诸如 if(value)
, value 之类的表达式中被评估为 false?code> 和
!value
?
已经有一些关于 StackOverflow 上假值目的的讨论,但是没有列出所有错误值的详尽完整答案.
我在 MDN JavaScript Reference 上找不到任何完整的列表,我惊讶地发现在 JavaScript 中寻找完整的、权威的假值列表时,排名靠前的结果是博客文章,其中一些有明显的遗漏(例如,NaN
),并且没有一篇有像 StackOverflow 那样的格式,可以添加评论或替代答案来指出怪癖、惊喜、遗漏,错误或警告.所以,制作一个似乎是有道理的.
JavaScript 中的假值
假
Number
类型的零:0
和-0
、0.0
和十六进制形式0x0
(感谢 RBT)BigInt
的零 类型:0n
和0x0n
(2020 年新增,感谢 GetMeARemoteJob)""
、''
和``
- 长度为 0 的字符串null
未定义
NaN
document.all
(仅在 HTML 浏览器中)- 这是一个奇怪的问题.
document.all
是一个伪对象,typeof
为undefined
.它是 IE11 之前 IE 中的 Microsoft 专有功能,并被添加到 HTML 规范作为故意违反 JavaScript 规范",以便为 IE 编写的站点不会在尝试访问时中断,例如document.all.something
;这是错误的,因为if (document.all)
曾经是在条件注释之前检测 IE 的流行方法.请参阅为什么 document.all 是虚假的?了解详情
- 这是一个奇怪的问题.
虚假"只是意味着 JavaScript 的内部 ToBoolean
函数返回 false
. ToBoolean
是 !value
的基础,value ?... : ...;
和 if (value)
.这是它的官方规范(2020年工作草案)(仅自 1997 年的第一个 ECMAscript 规范 添加了 ES6 的符号,它们总是真实的,以及 BigInt
,上面提到:
参数类型 | 结果 |
---|---|
未定义 | 返回false . |
空 | 返回false . |
布尔值 | 返回参数. |
数量 | 如果参数为+0 、-0 或NaN ,则返回false ;否则返回 true . |
字符串 | 如果参数是空的String (长度为零),返回false ;否则返回 true . |
BigInt | 如果参数为0n ,返回false ;否则返回 true . |
符号 | 返回true . |
对象 | 返回true . |
与 ==
的比较(松散相等)
值得讨论虚假值的 与 = 的松散比较=
,它使用 ToNumber()
并且由于潜在的差异可能会引起一些混淆.他们实际上形成了三组:
false, 0, -0, "", ''
都用==
相互匹配- 例如
false == ""
,'' == 0
因此4/2 - 2 == 'some string'.slice(11);
- 例如
null, undefined
与==
匹配- 例如
null == undefined
但undefined != false
- 还值得一提的是,虽然
typeof null
返回'object'
,null
是 不是对象,这是一个长期存在的错误/怪癖,未修复以保持兼容性.它不是真正的对象,并且对象是真实的(除了在 HTML 中实现 Javascript 时的故意违反"document.all
)
- 例如
NaN
不匹配任何东西,与==
或===
,甚至它本身都不匹配- 例如
NaN != NaN
,NaN !== NaN
,NaN != false
,NaN != null
莉>
- 例如
使用严格相等"(====
),没有这样的分组.只有false
===
false
.
这是许多开发人员和许多样式指南(例如 standardjs)更喜欢 == 的原因之一=
并且几乎从不使用 ==
.
实际值== false
真实"只是意味着 JavaScript 的内部 ToBoolean
函数返回 true
.一个需要注意的 Javascript 怪癖(以及另一个更喜欢 ===
而不是 ==
的好理由):可能有一个值为真(ToBoolean
返回 true
),但也== false
.
您可能认为 if (value && value == false) alert('Huh?')
是不可能发生的逻辑上的不可能,但它会发生,因为:>
"0"
和'0'
- 它们是非空字符串,是真实的,但 Javascript 的==
匹配具有等效字符串的数字(例如42 == 42"
).由于0 == false
,如果0"== 0
,"0"== 错误
.new Number(0)
和new Boolean(false)
- 它们是真实的对象,但是==
看到它们的值,其中== false
.0 .toExponential();
- 一个具有等价于0
的数值的对象- 任何类似的构造都会为您提供包含在真实类型中的假相等值
[]
、[[]]
和[0]
(感谢 cloudfeet 用于 JavaScript 平等表链接)
一些更真实的值
这些只是一些人可能认为是错误的一些值,但实际上是真实的.
-1
和所有非零负数' '
,""
,"false"
,'null'
... 所有 非空字符串,包括只是空格来自
typeof
的任何东西,它总是返回一个非空字符串,例如:typeof null
(返回一个字符串'object'
由于长期存在的错误/怪癖)typeof undefined
(返回一个字符串'undefined'
)
任何对象(浏览器中的故意违反"
document.all
除外).请记住,尽管typeof
另有暗示,但null
并不是真正的对象.示例:{}
[]
function(){}
或 <代码>() =>{}(任何函数,包括空函数)Error
和Error
的任何实例- 任何正则表达式
- 任何用
new
创建的东西(包括new Number(0)
和new Boolean(false)
)
任何符号
true
、1
、1"
和 [1]
返回 true
与 ==
相互比较.
What are the values in JavaScript that are 'falsey', meaning that they evaluate as false in expressions like if(value)
, value ?
and !value
?
There are some discussions of the purpose of falsey values on Stack Overflow already, but no exhaustive complete answer listing what all the falsey values are.
I couldn't find any complete list on MDN JavaScript Reference, and I was surprised to find that the top results when looking for a complete, authoritative list of falsey values in JavaScript were blog articles, some of which had obvious omissions (for example, NaN
), and none of which had a format like Stack Overflow's where comments or alternative answers could be added to point out quirks, surprises, omissions, mistakes or caveats. So, it seemed to make sense to make one.
Falsey values in JavaScript
false
- Zero of
Number
type:0
and also-0
,0.0
, and hex form0x0
(thanks RBT) - Zero of
BigInt
type:0n
and0x0n
(new in 2020, thanks GetMeARemoteJob) ""
,''
and``
- strings of length 0null
undefined
NaN
document.all
(in HTML browsers only)- This is a weird one.
document.all
is a falsey object, withtypeof
asundefined
. It was a Microsoft-proprietory function in IE before IE11, and was added to the HTML spec as a "willful violation of the JavaScript specification" so that sites written for IE wouldn't break on trying to access, for example,document.all.something
; it's falsy becauseif (document.all)
used to be a popular way to detect IE, before conditional comments. See Why is document.all falsy? for details
- This is a weird one.
"Falsey" simply means that JavaScript's internal ToBoolean
function returns false
. ToBoolean
underlies !value
, value ? ... : ...;
and if (value)
. Here's its official specification (2020 working draft) (the only changes since the very first ECMAscript specification in 1997 are the addition of ES6's Symbols, which are always truthy, and BigInt
, mentioned above:
Argument type Result Undefined Return false
.Null Return false
.Boolean Return argument. Number If argument is +0
,-0
, orNaN
, returnfalse
; otherwise returntrue
.String If argument is the empty String
(its length is zero), returnfalse
; otherwise returntrue
.BigInt If argument is 0n
, returnfalse
; otherwise returntrue
.Symbol Return true
.Object Return true
.
Comparisons with ==
(loose equality)
It's worth talking about falsy values' loose comparisons with ==
, which uses ToNumber()
and can cause some confusion due to the underlying differences. They effectively form three groups:
false, 0, -0, "", ''
all match each other with==
- e.g.
false == ""
,'' == 0
and therefore4/2 - 2 == 'some string'.slice(11);
- e.g.
null, undefined
match with==
- e.g.
null == undefined
butundefined != false
- It's also worth mentioning that while
typeof null
returns'object'
,null
is not an object, this is a longstanding bug/quirk that was not fixed in order to maintain compatibility. It's not a true object, and objects are truthy (except for that "wilful violation"document.all
when Javascript is implemented in HTML)
- e.g.
NaN
doesn't match anything, with==
or===
, not even itself- e.g.
NaN != NaN
,NaN !== NaN
,NaN != false
,NaN != null
- e.g.
With "strict equality" (===
), there are no such groupings. Only false
===
false
.
This is one of the reasons why many developers and many style guides (e.g. standardjs) prefer ===
and almost never use ==
.
Truthy values that actually == false
"Truthy" simply means that JavaScript's internal ToBoolean
function returns true
. A quirk of Javascript to be aware of (and another good reason to prefer ===
over ==
): it is possible for a value to be truthy (ToBoolean
returns true
), but also == false
.
You might think if (value && value == false) alert('Huh?')
is a logical impossibility that couldn't happen, but it will, for:
"0"
and'0'
- they're non-empty strings, which are truthy, but Javascript's==
matches numbers with equivalent strings (e.g.42 == "42"
). Since0 == false
, if"0" == 0
,"0" == false
.new Number(0)
andnew Boolean(false)
- they're objects, which are truthy, but==
sees their values, which== false
.0 .toExponential();
- an object with a numerical value equivalent to0
- Any similar constructions that give you a false-equaling value wrapped in a type that is truthy
[]
,[[]]
and[0]
(thanks cloudfeet for the JavaScript Equality Table link)
Some more truthy values
These are just a few values that some people might expect to be falsey, but are actually truthy.
-1
and all non-zero negative numbers' '
," "
,"false"
,'null'
... all non-empty strings, including strings that are just whitespaceAnything from
typeof
, which always returns a non-empty string, for example:typeof null
(returns a string'object'
due to a longstanding bug/quirk)typeof undefined
(returns a string'undefined'
)
Any object (except that "wilful violation"
document.all
in browsers). Remember thatnull
isn't really an object, despitetypeof
suggesting otherwise. Examples:{}
[]
function(){}
or() => {}
(any function, including empty functions)Error
and any instance ofError
- Any regular expression
- Anything created with
new
(includingnew Number(0)
andnew Boolean(false)
)
Any Symbol
true
, 1
, "1"
and [1]
return true
when compared to each other with ==
.
这篇关于JavaScript 中的所有错误值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!