为什么+符号是javascript中的例外?

Par*_*war 3 javascript dynamic-typing implicit-conversion

我这样做了

> 5 + 2 // 7, this is correct 

> 5 - 2 // 3 , obviously 

> 5 - "2" // 3 , ohh, that's awesome 

> 5 % "2" // 1 , :)

> 5 / "2" // 2.5,looks like 2 is automatically converted to integer.Perfect!

> 5 + "2" // "52" Really? 
Run Code Online (Sandbox Code Playgroud)

确定性,额外的东西正在加号.那是什么,为什么?

the*_*eye 6

根据ECMA 5.1二元+算子标准规范,

7. If Type(lprim) is String or Type(rprim) is String, then
      Return the String that is the result of concatenating ToString(lprim)
      followed by ToString(rprim)
Run Code Online (Sandbox Code Playgroud)

因此,如果其中一个操作数的类型为String,则标准要求实现将两个操作数转换为字符串类型并将它们连接起来.

注意:但是一元+运算符对字符串的行为不同.它将字符串转换为数字.

1. Let expr be the result of evaluating UnaryExpression.
2. Return ToNumber(GetValue(expr)).
Run Code Online (Sandbox Code Playgroud)