从一道js笔试题到==运算符的简析(2)

作者:afc163 来源:蓝色理想 时间:2010-05-10 20:28:00 

看看ECMA-262(第80页)中怎么说的:

6.If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
7.If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

也就是说,布尔值会被首先转换为数字,然后进行比较。true的数字值为1,false为0。所以2和-1都不能和true相等。

进一步看下面这个例子:

<SCRIPT LANGUAGE="JavaScript">
var a = "undefined";
var b = "false";
var c = "";
function assert (aVar) {
if (aVar==true)     alert(true);
else     alert(false);
}
assert(a);
assert(b);
assert(c);
</SCRIPT>

运行代码框


按照前面的思路,true会被转换为1,所以三个语句都会返回false。运行一下,发现的确如此。

下面将if(aVar==true)改为if(aVar)。

运行代码框


这时的运行结果是true,true,false。因为Boolean("undefined")、Boolean("false")、Boolean("")的结果为true,true,false。非空字符串转换为布尔值true。

最后还有一个例子,解释当==两边为字符串和数字时的比较规律。

运行代码框

发现没,这个"001"==true是为true的。

因为true先被转换为1了。然后参考ECMA的规则:

4.If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
5.If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

字符串要被转换为数字,Number("001")的值也为1,所以结果为true。

标签:js,运算符,试题
0
投稿

猜你喜欢

  • PHP curl get post 请求的封装函数示例【get、post、put、delete等请求类型】

    2023-05-25 01:24:18
  • IE不支持overrideMimeType()方法,即使是IE7.

    2009-02-08 16:58:00
  • ASP.NET教程第二讲:安装ASP.NET

    2007-08-07 11:59:00
  • asp利用Split函数进行多关键字检索

    2011-03-16 11:10:00
  • Flash如何连接Mysql

    2010-11-11 11:57:00
  • 实现页面中按钮刷新的N种方法

    2007-02-03 11:06:00
  • 窥探jQuery——面向JavaScript程序员

    2008-06-17 14:35:00
  • 面包屑设计

    2009-07-07 11:17:00
  • 最小asp后门程序

    2011-04-03 10:35:00
  • 用ASP实现txt,doc,jpg等文件下载的函数

    2007-08-17 13:17:00
  • 用javascript实现Base64编码

    2008-03-04 16:51:00
  • Microsoft Enterprise Library 5.0 如何集成MyS

    2011-03-16 15:19:00
  • asp测字符串长度及截取定长字符串汉字的处理

    2007-10-12 13:14:00
  • 我们需要的是怎样的分页?

    2007-09-28 20:24:00
  • MySQL表设计优化与索引 (九)

    2010-10-25 20:16:00
  • 使用网际数据库浏览器在线维护Access数据库

    2008-05-23 13:05:00
  • XML教程:什么是XML及XML和HTML的区别

    2008-09-05 17:21:00
  • asp解决防止表单重复提交的方法

    2007-10-19 18:40:00
  • 纯CSS实现导航下拉菜单

    2007-11-25 15:11:00
  • XAMPP和Mysql共存的方法

    2010-12-03 16:34:00
  • asp之家 网络编程 m.aspxhome.com