JavaScript 类型转换 [英] JavaScript type casting
问题描述
考虑空的 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
:
在这种情况下,左边的类型是object,右边的类型是boolean.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 规范 的 §11.9.3所有血腥细节.
See §11.9.3 of the ECMAScript spec for all the gory details.
(!a)
:
在这种情况下,Javascript 将对象转换为布尔值 true,然后将其反转,结果为 false.
In this case Javascript converts the object to the boolean true, then inverts it, resulting in false.
这篇关于JavaScript 类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!