javascript 中的隐式强制

implicit coercion in javascript

我正在重新审视 javascript 中的隐式强制转换,并意识到我忽略了一些事情并需要对此进行澄清。

如果

var a = "5";
var b = 5;

a==b 将 return true

但是有两种可能的方法 a==b 可以给出真正的强制,对吗?可以是 5 == 5,也可以是 '5' == '5'。那么上面的示例实际发生了哪一个?

答案在规范中的 Abstract Equality Comparison Algorithm 中,具体为:

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

ToNumber(x) 之前的 ! 并不意味着否定,它是一个规范符号断言 ToNumber(x) 永远不会导致突然终止。)

是一个数值比较,"5"转换成5然后比较就完成了

基于抽象相等比较算法,操作数将首先尝试转换为数字。所以字符串 '5' 将被尝试转换为数字 5.

看看abstract equality algorithm.中的第6步和第7步,无论数字是什么类型,数字的操作数都会被转换为数字。

这里有描述:

2019 EcmaScript specifications - 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) If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.

2) If x is null and y is undefined, return true.

3) If x is undefined and y is null, return true.

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.

(...)

所以字符串被转换为数字,然后进行比较。

这可以通过下面的代码来证明:

"" == 0 // true
0 == "" // true

两者都 return 正确,因为空字符串被强制转换为数字 0。

如果反过来,0 将变为“0”(因为 0 ==“0”也为真)并且与空字符串的比较将 return 为假