开发者

Adding and Subtracting Numbers as Strings

开发者 https://www.devze.com 2023-01-02 07:20 出处:网络
I read the following on a question on SO: \'7\' + 4 gives \'74\', whereas \'7\' - 4 gives 3 in JavaScript

I read the following on a question on SO:

'7' + 4 gives '74', whereas '7' - 4 gives 3 in JavaScript

Why does th开发者_如何学运维is happen?


+ is the String concatenation operator so when you do '7' + 4 you're coercing 4 into a string and appending it. There is no such ambiguity with the - operator.

If you want to be unambiguous use parseInt() or parseFloat():

parseInt('7', 10) + 4

Why specify the radix to 10? So '077' isn't parsed as octal.


The '+' operator is defined for both strings and numbers, so when you apply it to a string and a number, the number will be converted so string, then the strings will be concatenated: '7' + 4 => '7' + '4' => '74' But '-' is only defined for numbers, not strings, so the string '7' will be converted to number: '7' - 4 => 7 - 4 => 3


The + operator is overloaded in JavaScript to perform concatenation and addition. The way JavaScript determines which operation to carry out is based on the operands. If one of the operands is not of class Number (or the number primitive type), then both will be casted to strings for concatenation.

3 + 3 = 6
3 + '3' = 33
'3' + 3 = 33
(new Object) + 3 = '[object Object]3'

The - operator, however, is only for numbers and thus the operands will always be cast to numbers during the operation.


Because + is for concentration, if you want to add two numbers you should parse them first parseInt() and - sign is for subtraction


The sign + in Javascript is interpreted as concatenation first then addition, due to the fact that the first part is a string ('7'). Thus the interpreter converts the 2nd part (4) into string and concatenate it.

As for '7' - 4, there is no other meaning other than subtraction, thus subtraction is done.

0

精彩评论

暂无评论...
验证码 换一张
取 消