JavaScript类型转换 [英] JavaScript type casting

查看:100
本文介绍了JavaScript类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑空JavaScript数组:

Consider empty JavaScript array:

var a = [];
alert(a == false); // shows true
alert(!a); // shows false!

如何解释?
什么是规则?

How to explain this? What are the rules?

推荐答案

http://forums.whirlpool.net.au/archive/966449

a == false

a == false:

在这种情况下,左侧的类型是object,右侧是布尔值。 Javascript首先将布尔值转换为数字,得到 0 。然后它将对象转换为原始,产生空字符串。接下来,它将空字符串与 0 进行比较。空字符串转换为数字,产生 0 ,其数值等于右侧的 0 侧,因此整个表达式的结果为 true

In this case, the type of the left-hand side is object, the type of the right-hand side is boolean. Javascript first converts the boolean to a number, yielding 0. Then it converts the object to a "primitive", yielding the empty string. Next it compares the empty string to 0. The empty string is converted to a number, yielding 0, which is numerically equal to the 0 on the right-hand side, so the result of the entire expression is true.

请参阅 ECMAScript规范所有的血腥细节。

See §11.9.3 of the ECMAScript spec for all the gory details.

(!a)

(!a):

布尔值true,然后反转,导致false。

In this case Javascript converts the object to the boolean true, then inverts it, resulting in false.

这篇关于JavaScript类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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