JavaScript 中的所有错误值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19839952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
All falsey values in JavaScript
提问by user56reinstatemonica8
What are the values in JavaScript that are 'falsey', meaning that they evaluate as false in expressions like if(value)
, value ?
and !value
?
JavaScript 中的 'falsey' 值是什么,这意味着它们在if(value)
,value ?
和等表达式中被评估为假!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.
Stack Overflow 上已经有一些关于伪值目的的讨论,但没有详尽的完整答案列出所有伪值是什么。
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.
我在 MDN JavaScript Reference 上找不到任何完整的列表,我惊讶地发现在 JavaScript 中寻找完整的、权威的虚假值列表时,排名靠前的结果是博客文章,其中一些有明显的遗漏(例如,NaN
),而且没有一个像 Stack Overflow 这样的格式,可以添加评论或替代答案来指出怪癖、惊喜、遗漏、错误或警告。所以,制作一个似乎是有道理的。
回答by user56reinstatemonica8
Falsey values in JavaScript
JavaScript 中的假值
false
- Zero of
Number
type:0
and also-0
,0.0
, and hex form0x0
(thanks RBT) - Zero of
BigInt
type:0n
and-0n
(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.
false
Number
类型零:0
还有-0
,0.0
和 hex 形式0x0
(感谢 RBT)BigInt
类型为零:0n
和-0n
(2020 年新增,感谢 GetMeARemoteJob)""
,''
和``
- 长度为 0 的字符串null
undefined
NaN
document.all
(仅在 HTML 浏览器中)- 这是一个奇怪的。
document.all
是一个 falsey 对象,带有typeof
asundefined
。在 IE11 之前,它是 IE 中的 Microsoft 专有功能,并作为“故意违反 JavaScript 规范”添加到HTML 规范中,以便为 IE 编写的站点不会在尝试访问时中断,例如document.all.something
;这是错误的,因为if (document.all)
曾经是在条件注释之前检测 IE 的流行方法。请参阅为什么 document.all 为假?详情
- 这是一个奇怪的。
"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 1997are the addition of ES6's Symbols, which are always truthy, and BigInt
, mentioned above:
“Falsey”只是意味着 JavaScript 的内部ToBoolean
函数返回false
. ToBoolean
基础!value
,value ? ... : ...;
和if (value)
. 这是它的官方规范(2020 年工作草案)(自1997 年第一个 ECMAscript 规范以来,唯一的变化是添加了ES6 的 Symbols,它们始终是真实的,并且BigInt
,如上所述:
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:
值得一提的是虚假值与 的松散比较==
,ToNumber()
由于潜在的差异,它使用并可能导致一些混淆。他们实际上形成了三组:
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/quirkthat 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.
false, 0, -0, "", ''
都相互匹配==
- 例如
false == ""
,'' == 0
因此4/2 - 2 == 'some string'.slice(11);
- 例如
null, undefined
匹配==
- 例如
null == undefined
但是undefined != false
- 这也是值得一提的是,虽然
typeof null
回报'object'
,null
是不是一个对象,这是一个长期的错误/怪癖这是不固定的,以保持兼容性。它不是真正的对象,并且对象是真实的(除了document.all
在 HTML 中实现 Javascript 时的“故意违反” )
- 例如
NaN
与==
或不匹配===
,甚至不匹配- 例如
NaN != NaN
,NaN !== NaN
,NaN != false
,NaN != null
- 例如
With "strict equality" (===
), there are no such groupings. Only false
===
false
.
对于“严格相等”( ===
),没有这样的分组。只有false
===
false
。
This is one of the reasons why many developers and many style guides (e.g. standardjs) prefer ===
and almost never use ==
.
这就是为什么许多开发人员和许多样式指南(例如standardjs)更喜欢===
并且几乎从不使用==
.
Truthy values that actually == false
真实值实际上 == 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
.
“真实”只是意味着 JavaScript 的内部ToBoolean
函数返回true
. Javascript的应用怪癖要知道的(和另一个很好的理由,更喜欢===
了==
):这是可能的值是truthy(ToBoolean
回报true
),而且还== false
。
You might think if (value && value == false) alert('Huh?')
is a logical impossibility that couldn't happen, but it will, for:
您可能认为这if (value && value == false) alert('Huh?')
是不可能发生的逻辑不可能性,但它会发生,因为:
"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 cloudfeetfor the JavaScript Equality Table link)
"0"
并且'0'
- 它们是非空字符串,它们是真实的,但 Javascript==
将数字与等效字符串匹配(例如42 == "42"
)。由于0 == false
, 如果"0" == 0
,"0" == false
.new Number(0)
并且new Boolean(false)
- 它们是对象,它们是真实的,但==
可以看到它们的值,其中== false
.0 .toExponential();
- 一个对象的数值相当于0
- 任何类似的构造都会为您提供包含在真实类型中的假相等值
[]
,[[]]
和[0]
(感谢cloudfeet提供的JavaScript 平等表链接)
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'
... allnon-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). Including:{}
[]
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
-1
和所有非零负数' '
," "
,"false"
,'null'
...所有非空字符串,包括只是空格的字符串来自 的任何内容
typeof
,它始终返回一个非空字符串,例如:typeof null
('object'
由于长期存在的错误/怪癖而返回一个字符串)typeof undefined
(返回一个字符串'undefined'
)
任何对象(
document.all
浏览器中的“故意违反”除外;请记住,null
尽管typeof
另有建议,但它并不是真正的对象)。包括:{}
[]
function(){}
或() => {}
(任何函数,包括空函数)Error
和任何实例Error
- 任何正则表达式
- 使用
new
(包括new Number(0)
和new Boolean(false)
)创建的任何内容
- 任何符号
true
, 1
, "1"
and [1]
return true
when compared to each other with ==
.
true
, 1
,"1"
和[1]
returntrue
与==
.
回答by RBT
Just to add to @user568458's list of falsy values:
只是添加到@user568458 的虚假值列表中:
In addition to integer number 0, the decimal number 0.0, 0.00 or any such zeroish number is also a falsy value.
var myNum = 0.0; if(myNum){ console.log('I am a truthy value'); } else { console.log('I am a falsy value'); }
Above code snippet prints
I am a falsy value
Similarly hex representation of the number 0 is also a falsy value as shown in below code snippet:
var myNum = 0x0; //hex representation of 0 if(myNum){ console.log('I am a truthy value'); } else { console.log('I am a falsy value'); }
Above code snippet again prints
I am a falsy value
.
除了整数 0,十进制数 0.0、0.00 或任何此类零值也是假值。
var myNum = 0.0; if(myNum){ console.log('I am a truthy value'); } else { console.log('I am a falsy value'); }
上面的代码片段打印
I am a falsy value
同样,数字 0 的十六进制表示也是一个假值,如下面的代码片段所示:
var myNum = 0x0; //hex representation of 0 if(myNum){ console.log('I am a truthy value'); } else { console.log('I am a falsy value'); }
上面的代码片段再次打印
I am a falsy value
.
回答by MrMcPlad
Don't forget about the non-empty string "false"
which evaluates to true
不要忘记"false"
评估为的非空字符串true
回答by GetMeARemoteJob
Addition to the topic, as of ES2020 we have a new value which is falsy, it's BigInt zero (0n):
除了主题之外,从 ES2020 开始,我们有一个新值,它是假的,它是 BigInt 零 (0n):
0n == false // true
-0n == false // true
So with this, we now have 7 "falsy" values in total (not including document.all as mentioned by user above since it's part of DOM and not JS).
因此,有了这个,我们现在总共有 7 个“假”值(不包括上面用户提到的 document.all,因为它是 DOM 而不是 JS 的一部分)。