在对象到布尔值的情况下,Javascript 中的类型强制如何? [英] How does Type Coercion in Javascript in the case of object to boolean?

查看:22
本文介绍了在对象到布尔值的情况下,Javascript 中的类型强制如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,(x == false) 应该和 !x 做同样的事情,因为它们都试图解释 x 作为布尔值,然后取反.

To the best of my knowledge, (x == false) should do the same thing as !x, as both of them try to interpret x as a boolean, and then negates it.

然而,当我尝试对此进行测试时,我开始出现一些非常奇怪的行为.

However, when I tried to test this out, I started getting some extremely strange behavior.

例如:

false == []false == ![] 都返回 true.

false == [] and false == ![] both return true.

另外

false == undefinedtrue == undefined 都返回 false,同样

false == undefined and true == undefined both return false, as does

false == Infinitytrue == Infinity

false == NaNtrue == NaN.

这里到底发生了什么?

http://jsfiddle.net/AA6np/1/

推荐答案

都在这里:http://es5.github.com/#x11.9.3

对于false == []的情况:

  • false 被转换为数字 (0),因为这总是用布尔值完成的.
  • [] 通过调用[].valueOf().toString() 被转换为原语,即空字符串.
  • 0 == "" 然后通过将空字符串转换为数字来评估,并且因为其结果也是 0,所以 false == [] 是是的.
  • false is converted to a number (0), because that is always done with booleans.
  • [] is converted to a primitive by calling [].valueOf().toString(), and that is an empty string.
  • 0 == "" is then evaluated by converting the empty string to a number, and because the result of that is also 0, false == [] is true.

对于false == ![]的情况:

  • 逻辑非运算符 ! 通过返回与 ToBoolean(GetValue(expr))
  • 相反
  • ToBoolean() 对于任何对象始终为真,所以 ![] 计算结果为 false(因为 !true = false),因此是 false == ![]也是如此.
  • The logical not operator ! is performed by returning the opposite of ToBoolean(GetValue(expr))
  • ToBoolean() is always true for any object, so ![] evaluates to false (because !true = false), and therefore is false == ![] also true.

(false == undefined) === false(true == undefined) === false 更简单:

  • falsetrue 再次转换为数字(分别为 0 和 1).
  • 因为 undefined 不能与数字进行比较,所以链会冒泡到默认结果,即 false.
  • false and true are again converted to numbers (0 and 1, respectively).
  • Because undefined cannot be compared to a number, the chain bubbles through to the default result and that is false.

其他两种情况的计算方式相同:首先将布尔值转换为数字,然后将其与其他数字进行比较.由于 0 和 1 都不等于无穷大或不是数字,因此这些表达式的计算结果也为 false.

The other two cases are evaluated the same way: First Boolean to Number, and then compare this to the other number. Since neither 0 nor 1 equals Infinity or is Not A Number, those expressions also evaluate to false.

这篇关于在对象到布尔值的情况下,Javascript 中的类型强制如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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