문제

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 ?

도움이 되었습니까?

해결책

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)).

다른 팁

+ 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.

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top