大家来看看,对于这个的理解。1.2 == true , 大家说是false还是true? 为什么会这样呢?
发布于 8 年前 作者 21614306 7335 次浏览 来自 问答

QQ截图20160415111518.jpg

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

1.2 == true 是false

11 回复

QQ截图20160415112230.jpg

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

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(===)

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

@ncuzp [] +9 => “9” 怎么解释。

QQ截图20160415120735.jpg

真心有点诡异。

@SinalVee 3Q , 我再看看。

这是为啥?

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

var a = {};
a + 9 => [object Object]9

@21614306 第一个:[] => ‘’ => 0 第二个: 由第一个可知 第三个: “0” => 0 第四个: 上面已解释

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

回到顶部