admin管理员组

文章数量:1302403

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

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
Share Improve this question edited Jan 2, 2020 at 16:47 isherwood 61.1k16 gold badges120 silver badges169 bronze badges asked Oct 31, 2017 at 2:20 limitlessriverlimitlessriver 8011 gold badge7 silver badges9 bronze badges 2
  • 3 1 - - 1 == 1 - (-1) == 1 + 1 ... doing a - on a string will coerce the string to a Number – Jaromanda X Commented Oct 31, 2017 at 2:21
  • Not what you're asking about, but as a natural next step you may like to read about the unary plus operator. +"1" + +"1" => 2, but "1" + "1" => "11". – nnnnnn Commented Oct 31, 2017 at 2:27
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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 pute their difference (2).

本文标签: Minus () operator on strings in JavaScriptStack Overflow