JavaScript中哪些值是“假的”,即它们在if(value), value等表达式中被计算为假的?和!价值?


在Stack Overflow上已经有一些关于假值的目的的讨论,但是没有详尽的完整的答案列出所有假值是什么。

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


当前回答

在@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.

其他回答

除了主题之外,从ES2020开始,我们有了一个假的新值,它是BigInt 0 (0n):

0n == false // true
-0n == false // true
0n === false // false
-0n === false // false

因此,我们现在总共有7个“假”值(不包括document)。如上所述,因为它是DOM的一部分,而不是JS)。

在@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.

不要忘记非空字符串“false”,它的结果是true

JavaScript中的Falsey值

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”仅仅意味着JavaScript内部的ToBoolean函数返回false。ToBoolean的基础!value, value ?... :……;和if (value)。以下是它的官方规范(2020年工作草案)(自1997年第一个ECMAscript规范以来,唯一的变化是增加了ES6的符号,这是始终正确的,以及上面提到的BigInt:

参数类型 结果 未定义的 返回false。 零 返回false。 布尔 返回参数。 数量 如果参数为+0,-0或NaN,返回false;否则返回true。 字符串 如果参数为空字符串(其长度为零),返回false;否则返回true。 长整型数字 如果参数为0n,返回false;否则返回true。 象征 返回true。 对象 返回true。


与==的比较(松散相等)

值得讨论的是假值与==的松散比较,它使用ToNumber(),并可能由于潜在的差异而导致一些混乱。他们有效地形成了三个群体:

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

对于“严格相等”(===),就没有这样的分组。只有false === false。

这就是为什么许多开发人员和许多风格指南(例如standardjs)更喜欢===而几乎从不使用==的原因之一。


真值实际上==假

“Truthy”仅仅意味着JavaScript内部的ToBoolean函数返回true。Javascript需要注意的一个怪癖(也是更喜欢===而不是==的另一个很好的理由):值可能是真值(ToBoolean返回真值),但也可能是==假值。

你可能认为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 cloudfeet for the JavaScript Equality Table link)


一些更真实的价值观

有些人可能认为这些价值观是错误的,但实际上是正确的。

-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: 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 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"和[1]用==比较时返回True。