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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:00:26  来源:igfitidea点击:

All falsey values in JavaScript

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 Numbertype: 0and also -0, 0.0, and hex form 0x0(thanks RBT)
  • Zero of BigInttype: 0nand -0n(new in 2020, thanks GetMeARemoteJob)
  • "", ''and ``- strings of length 0
  • null
  • undefined
  • NaN
  • document.all(in HTML browsers only)
    • This is a weird one. document.allis a falsey object, with typeofas undefined. 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 because if (document.all)used to be a popular way to detect IE, before conditional comments. See Why is document.all falsy?for details
  • false
  • Number类型零:0还有-0,0.0和 hex 形式0x0感谢 RBT
  • BigInt类型为零:0n-0n(2020 年新增,感谢 GetMeARemoteJob
  • "",''``- 长度为 0 的字符串
  • null
  • undefined
  • NaN
  • document.all(仅在 HTML 浏览器中)
    • 这是一个奇怪的。document.all是一个 falsey 对象,带有typeofas undefined。在 IE11 之前,它是 IE 中的 Microsoft 专有功能,并作为“故意违反 JavaScript 规范”添加到HTML 规范中,以便为 IE 编写的站点不会在尝试访问时中断,例如document.all.something;这是错误的,因为if (document.all)曾经是在条件注释之前检测 IE 的流行方法。请参阅为什么 document.all 为假?详情

"Falsey" simply means that JavaScript's internal ToBooleanfunction returns false.ToBooleanunderlies !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,如上所述:

Undefined: Return false. Null: Return false. Boolean: Return argument. Number: If argument is +0, -0, or NaN, return false; otherwise return true. String: If argument is the empty String (its length is zero), return false; otherwise return true. BigInt: If argument is 0n, return false; otherwise return true. Symbol: Return true. Object: Return true.

未定义:返回假。 空:返回假。 布尔值:返回参数。 Number:如果参数是 +0、-0 或 NaN,则返回 false; 否则返回真。 String:如果参数是空字符串(其长度为零),则返回false; 否则返回真。 BigInt:如果参数为 0n,则返回 false; 否则返回真。 符号:返回真。 对象:返回真。



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 == "", '' == 0and therefore 4/2 - 2 == 'some string'.slice(11);
  • null, undefinedmatch with ==
    • e.g. null == undefinedbut undefined != false
    • It's also worth mentioning that while typeof nullreturns 'object', nullis 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.allwhen Javascript is implemented in HTML)
  • NaNdoesn't match anything, with ==or ===, not even itself
    • e.g. NaN != NaN, NaN !== NaN, NaN != false, NaN != null
  • 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 ToBooleanfunction 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 (ToBooleanreturns 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"). Since 0 == false, if "0" == 0, "0" == false.
  • new Number(0)and new Boolean(false)- they're objects, which are truthy, but ==sees their values, which == false.
  • 0 .toExponential();- an object with a numerical value equivalent to 0
  • 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.

这些只是一些人可能认为是错误的一些值,但实际上是真实的。

  • -1and all non-zero negative numbers
  • ' ', " ", "false", 'null'... allnon-empty strings, including strings that are just whitespace
  • Anything from typeof, which always returns a non-empty string, for example:

  • Any object (except that "wilful violation" document.allin browsers; remember that nullisn't really an object despite typeofsuggesting otherwise). Including:

    • {}
    • []
    • function(){}or () => {}(any function, including empty functions)
    • Errorand any instance of Error
    • Any regular expression
    • Anything created with new(including new Number(0)and new Boolean(false))
  • Any Symbol
  • -1和所有非零负数
  • ' ', " ", "false", 'null'...所有非空字符串,包括只是空格的字符串
  • 来自 的任何内容typeof,它始终返回一个非空字符串,例如:

  • 任何对象(document.all浏览器中的“故意违反”除外;请记住,null尽管typeof另有建议,但它并不是真正的对象)。包括:

    • {}
    • []
    • function(){}() => {}(任何函数,包括空函数)
    • Error和任何实例 Error
    • 任何正则表达式
    • 使用new(包括new Number(0)new Boolean(false))创建的任何内容
  • 任何符号

true, 1, "1"and [1]return truewhen 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 的一部分)。