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
2 Answers
Reset to default 6As 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
版权声明:本文标题:Minus (-) operator on strings in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741706804a2393608.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论