CNode

大家来看看,对于这个的理解。1.2 == true , 大家说是false还是true? 为什么会这样呢?

问答
221614306发布于10 年前最后回复10 年前11 回复8280 浏览0 收藏

QQ截图20160415111518.jpg

大家对于这里的理解是啥?

1.2 == true 是false

查看回复

回复 (11)

2
21614306#1·10 年前

QQ截图20160415112230.jpg

看了犀牛书看到的, 想想大家是怎么理解的。

S
SinalVee#2·10 年前

ECMA-262 7.2.12 Abstract Equality Comparison(==) 为了方便copy过来

7.2.12 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
1. ReturnIfAbrupt(x).
2. ReturnIfAbrupt(y).
3. If Type(x) is the same as Type(y), then
	Return the result of performing Strict Equality Comparison x === y.
4. If x is null and y is undefined, return true.
5. If x is undefined and y is null, return true.
6. If Type(x) is Number and Type(y) is String,
	return the result of the comparison x == ToNumber(y).
7. If Type(x) is String and Type(y) is Number,
	return the result of the comparison ToNumber(x) == y.
8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
	return the result of the comparison x == ToPrimitive(y).
11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
	return the result of the comparison ToPrimitive(x) == y.
12. Return false.

'1.2' == true符合第9条,返回'1.2' == ToNumber(true),即'1.2' == 1 符合第7条,返回ToNumber('1.2') == 1,即1.2 == 1 符合第3条,返回1.2 === 1 后面就是===严格相等了,不赘述了,下面是链接 ECMA-262 7.2.13 Strict Equality Comparison(===)

N
ncuzp#3·10 年前

根据上面的解答简单归结起来就是,非Number 转换为Number 来比较,对象类型转换为原始类型来处理

2
21614306#5·10 年前

QQ截图20160415120735.jpg

真心有点诡异。

2
21614306#7·10 年前

QQ截图20160415121441.jpg

2
21614306#8·10 年前

这是为啥?

N
ncuzp#9·10 年前
引用 21614306

@21614306 这个是因为{}对象字面量这个在浏览器中会被解析为代码块而不是对象,浏览器会尝试执行代码块,而上面并没有代码执行所以第一个只返回了9, 对于第二个,[]的Primitive的值会调用toString方式转换为空字符串,然后空字符串和9相加就是字符串"9"了,如果代码如下:

var a = {};
a + 9 => [object Object]9
N
ncuzp#10·10 年前
引用 21614306真心有点诡异。

@21614306 第一个:[] => '' => 0 第二个: 由第一个可知 第三个: "0" => 0 第四个: 上面已解释

Z
zstxt1989#11·10 年前

只要记得两点: bool 对应 0和1 数字和字符串比较,会把字符串转化为数字,再比较两者大小。 true == "1.2" 相当于 1 == "1.2" 相当于 1 == 1.2 结果是false

参与回复
登录后即可参与回复。登录