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

时间:2014-03-22 03:26:44

标签: javascript implicit-conversion dynamic-typing

我做了这个

> 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? 
确定,加号会带来额外的影响。那是什么?为什么?

4 个答案:

答案 0 :(得分:6)

根据ECMA 5.1 Standard Specification for Binary + operator

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)

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

注意:unary + operator对字符串的行为有所不同。它将字符串转换为数字。

1. Let expr be the result of evaluating UnaryExpression.
2. Return ToNumber(GetValue(expr)).

答案 1 :(得分:1)

在字符串的情况下,

+用于连接。它仅用于数字的添加。

对于您列出的所有其他运算符,它们没有这种双重用途,字符串"2"被强制转换为数字。

答案 2 :(得分:0)

在这些操作中,+符号是对数字执行操作和对字符串执行不同操作的唯一符号。所有其他符号仅对数字起作用,因此类型推断更简单。

也就是说,如果+一元运算符,那么it converts the argument to a number

答案 3 :(得分:0)

  

5 +" 2" //" 52"真?

5作为数字 " 2"作为文本

所以在Javascript +联系两个值

  

5 +" 2"成为7你需要使用parseFloat或parseInt

     

5 + parseInt(" 2")= 7