空数组是虚假的,但是[]吗? 0:1等于0 [英] Empty array is falsy, yet [] ? 0 : 1 evaluates to 0
问题描述
如果空数组[]
在JavaScript中为 falsy ,则为什么当在三元运算符中用作谓词时,该运算符等于第一个选项?
If the empty array []
is falsy in JavaScript then why, when used as the predicate in the ternary operator, the operator evals to the first option?
console.log([] == false); // prints true
console.log([] ? 0 : 1); // prints 0 !
推荐答案
首先,一个空数组不是falsey,要使用!!
获取它的实际布尔值前缀,例如:console.log(!![]) // true
First, an empty array is not falsey, to get the actual boolean value prefix it with !!
such as: console.log(!![]) // true
您从第一次比较中得到的结果是强制性的.通过==
操作数进行左右比较时,JavaScript尝试将输入强制为通用类型,如下所示:
The result you got from the first comparison is due to coercion. When doing a left vs. right comparison via the ==
operand JavaScript attempts to coerce the inputs to a common type, as follows:
- 发现右侧为
Boolean
,因此将其转换为Number
值,导致比较为[] == 0
. - 由于左侧是
Object
,因此将其转换为基本体.在这种情况下,通过[].toString()
通过String
进行比较,导致比较结果为"" == 0
. - 由于左侧是
String
,因此将其转换为number
值,从而导致0 == 0
. - 由于双方都是
Number
原语,因此将它们的值进行比较,从而得出真实情况
- The right-hand side is found to be
Boolean
so it is converted to aNumber
value, resulting in the comparison being[] == 0
. - Since the left-hand side is an
Object
it is converted to a primitive; in this case aString
via[].toString()
, resulting in the comparison being"" == 0
. - Since the left-hand side is a
String
, it gets converted to anumber
value resulting in0 == 0
. - Since both sides are
Number
primitives, their values are compared, resulting in a truthy condition
使用第二个表达式时,没有右手可以比较,因此它仅测试输入是否为真.数组不是null
,undefined
,0
,""
或NaN
,因此是正确的.
With the second expression, there is no right-hand to compare to, so it simply tests if the input is truthy. The array is not null
, undefined
, 0
, ""
or NaN
, therefore, it is truthy.
要在两个输入之间强制进行非强制比较,应使用===
操作数.
To force a non-coercive comparison between two inputs you should use the ===
operand.
这篇关于空数组是虚假的,但是[]吗? 0:1等于0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!