JavaScript 中的所有错误值 [英] All falsey values in JavaScript

查看:17
本文介绍了JavaScript 中的所有错误值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript 中哪些值是falsey",这意味着它们在诸如 if(value), value 之类的表达式中被评估为 false?code> 和 !value?

<小时>

已经有一些关于 StackOverflow 上假值目的的讨论,但是没有列出所有错误值的详尽完整答案.

我在 MDN JavaScript Reference 上找不到任何完整的列表,我惊讶地发现在 JavaScript 中寻找完整的、权威的假值列表时,排名靠前的结果是博客文章,其中一些有明显的遗漏(例如,NaN),并且没有一篇有像 StackOverflow 那样的格式,可以添加评论或替代答案来指出怪癖、惊喜、遗漏,错误或警告.所以,制作一个似乎是有道理的.

解决方案

JavaScript 中的假值

  • Number 类型的零:0-00.0 和十六进制形式 0x0 (感谢 RBT)
  • BigInt 的零 类型:0n0x0n(2020 年新增,感谢 GetMeARemoteJob)
  • ""''`` - 长度为 0 的字符串
  • null
  • 未定义
  • NaN
  • document.all(仅在 HTML 浏览器中)
    • 这是一个奇怪的问题.document.all 是一个伪对象,typeofundefined.它是 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-0NaN,则返回false;否则返回 true.
字符串如果参数是空的String(长度为零),返回false;否则返回 true.
BigInt如果参数为0n,返回false;否则返回 true.
符号返回true.
对象返回true.


== 的比较(松散相等)

值得讨论虚假值的 = 的松散比较=,它使用 ToNumber() 并且由于潜在的差异可能会引起一些混淆.他们实际上形成了三组:

使用严格相等"(====),没有这样的分组.只有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 的任何东西,它总是返回一个非空字符串,例如:

  • 任何对象(浏览器中的故意违反"document.all 除外).请记住,尽管 typeof 另有暗示,但 null 并不是真正的对象.示例:

    • {}
    • []
    • function(){}<代码>() =>{}(任何函数,包括空函数)
    • ErrorError
    • 的任何实例
    • 任何正则表达式
    • 任何用 new 创建的东西(包括 new Number(0)new Boolean(false))
  • 任何符号

true11"[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 form 0x0 (thanks RBT)
  • Zero of BigInt type: 0n and 0x0n (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.all is a falsey object, with typeof as 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

"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, 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.


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 therefore 4/2 - 2 == 'some string'.slice(11);
  • null, undefined match with ==
    • e.g. null == undefined but undefined != 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)
  • NaN doesn't match anything, with == or ===, not even itself
    • e.g. NaN != NaN, NaN !== NaN, NaN != false, NaN != null

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"). 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 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 whitespace

  • Anything from typeof, which always returns a non-empty string, for example:

  • Any object (except that "wilful violation" document.all in browsers). Remember that null isn't really an object, despite typeof suggesting otherwise. Examples:

    • {}
    • []
    • function(){} or () => {} (any function, including empty functions)
    • Error and any instance of Error
    • Any regular expression
    • Anything created with new (including new Number(0) and new Boolean(false))
  • Any Symbol

true, 1, "1" and [1] return true when compared to each other with ==.

这篇关于JavaScript 中的所有错误值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆