网络编程
位置:首页>> 网络编程>> JavaScript>> 从一道js笔试题到==运算符的简析(2)

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

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

标签:js,运算符,试题

看看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。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com