why + sign is the exception in javascript?

帅比萌擦擦* 提交于 2019-12-12 14:43:16

问题


i did this

> 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? 

Certainty, something extra is going on with plus sign. What's that and why ?


回答1:


As per the 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)

So, if either of the operands are of type String, then the standard mandates the implementations to convert both the operands to string type and concatenate them.

Note: But the unary + operator behaves differently with strings. It converts the strings to numbers.

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



回答2:


+ is used for concatenation in the case of strings. It is only used for addition in the case of numbers.

For all the other operators you list, they do not have this dual purpose and the string "2" is cast to a number.




回答3:


5 + "2" // "52" Really?

YES

5 as A number "2" as a text

So In Javascript + CONTACTING TWO values

5 + "2" to become 7 you need to use parseFloat or parseInt

5 + parseInt("2") = 7




回答4:


Of these operations, the + sign is the only symbol that does an operation on numbers and a different operation on strings. All the other symbols only operate on numbers, so type-inference is much simpler.

That said, if + is a unary operator, then it converts the argument to a number.



来源:https://stackoverflow.com/questions/22573070/why-sign-is-the-exception-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!