空数组是虚假的,但是[]吗? 0:1等于0 [英] Empty array is falsy, yet [] ? 0 : 1 evaluates to 0

查看:57
本文介绍了空数组是虚假的,但是[]吗? 0:1等于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:

  1. 发现右侧为Boolean,因此将其转换为Number值,导致比较为[] == 0.
  2. 由于左侧是Object,因此将其转换为基本体.在这种情况下,通过[].toString()通过String进行比较,导致比较结果为"" == 0.
  3. 由于左侧是String,因此将其转换为number值,从而导致0 == 0.
  4. 由于双方都是Number原语,因此将它们的值进行比较,从而得出真实情况
  1. The right-hand side is found to be Boolean so it is converted to a Number value, resulting in the comparison being [] == 0.
  2. Since the left-hand side is an Object it is converted to a primitive; in this case a String via [].toString(), resulting in the comparison being "" == 0.
  3. Since the left-hand side is a String, it gets converted to a number value resulting in 0 == 0.
  4. Since both sides are Number primitives, their values are compared, resulting in a truthy condition

使用第二个表达式时,没有右手可以比较,因此它仅测试输入是否为真.数组不是nullundefined0""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.

Ecma标准第6版在强制性上的条目
JS强制解释了

这篇关于空数组是虚假的,但是[]吗? 0:1等于0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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