空JavaScript阵列的布尔值冲突 [英] Conflicting boolean values of an empty JavaScript array

查看:97
本文介绍了空JavaScript阵列的布尔值冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么以下两个陈述都评估为 true

Can anyone explain why the following two statements both evaluate as true?

[] == false

!![]

这个问题纯粹出于好奇,为什么会发生这种情况而不是如何最好地测试数组是否为空。

This question is purely out of curiosity of why this happens and not about how to best test if an array is empty.

推荐答案

第一个:

[] == false

== 运算符对其操作数进行类型转换,在这种情况下,双方都转换为数字,在抽象平等比较算法将是:

The == operator does type conversion to its operands, in this case the both sides are converted to Number, the steps taken on the Abstract Equality Comparison Algorithm would be:


  • object == boolean

  • object == number

  • string == number

  • number == number

  • object == boolean
  • object == number
  • string == number
  • number == number

代码:

[] == false; // convert false to Number
[] == 0;     // convert [] to Primitive (toString/valueOf)
"" == 0;     // convert "" to Number
0  == 0;     // end

第二次比较, [] 转换为原始,它们的 valueOf toString 方法被执行,但是因为 valueOf 在Array对象上,返回对象本身(继承自 Object.prototype ),然后 toString 使用方法。

The second comparison, [] is converted to primitive, their valueOf and toString methods are executed, but since valueOf on Array objects, returns the object itself (is inherited from Object.prototype), then the toString method is used.

如您所见,两个操作数都转换为Number,两者都为零,例如:

At the end as you see, both operands are converted to Number, and both yield zero, for example:

Number([]) == 0;
Number(false) == 0;

当转换为Number时,空数组产生零,因为其字符串表示形式为空字符串:

And empty array produces zero when converted to Number because its string representation is an empty string:

[].toString(); // ""

空字符串转换为数字,产生零:

And an empty string converted to Number, yields zero:

+""; // 0

现在,双重否定( !! [] )生成true,因为所有对象实例都是真实的:

Now, the double negation (!![]) produces true because all object instances are truthy:

![];  // false, [] is truthy
!![]; // true, negation

falsey 的唯一值是:


  • null

  • 未定义

  • 0

  • NaN

  • (空字符串)

  • false

  • null
  • undefined
  • 0
  • NaN
  • "" (an empty string)
  • false

其他任何东西都会产生 true 转换为布尔值时。

Anything else will produce true when converted to Boolean.

参见:

  • JavaScript Coercion Tool

这篇关于空JavaScript阵列的布尔值冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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