JavaScript 类型转换 [英] JavaScript type casting

查看:19
本文介绍了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:

在这种情况下,左边的类型是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屋!

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