问题
I was taking this JavaScript Quiz and found this question -
"1" - - "1";
The result of this statement is 2.
Can anyone explain what is going on here?
I also found that with even - the addition of strings take place but with odd - subtraction. This only happens when a number is a string.
Here are some more eamples-
"1" - "1" => 0
"1" - - "1" => 2
"1" - - - "1" => 0
"1" - - - - "1" => 2
"a" - "b" => NaN
回答1:
The expression is equivalent to "1" - (-"1"). The unary minus will convert its argument ("1") to a number (1) and take its inverse (-1). The binary minus will convert its arguments ("1" and -1) to numbers (1 and -1) and compute their difference (2).
回答2:
As per ecma script spec :
12.8.4 The Subtraction Operator ( ‐ )
5. Let lnum be ToNumber(lval).
6. Let rnum be ToNumber(rval).
7. Return the result of applying the subtraction operation to lnum and rnum
What that means In case of subtraction both operands are converted to a number.
So "1" - "1" actually means ToNumber("1")- ToNumber("1") but in +, since it's "overloaded" (as java guy would call it), it goes to "concatenation in case of string.
来源:https://stackoverflow.com/questions/47026942/minus-operator-on-strings-in-javascript