Adding and subtracting strings and numbers in Javascript - auto type conversion?

前端 未结 5 1746
抹茶落季
抹茶落季 2020-12-04 01:52

Let\'s look at the following Javascript code.



        
相关标签:
5条回答
  • 2020-12-04 02:20

    If you don't want this, an easy fix is: (1*'2')+8 JSYK

    0 讨论(0)
  • 2020-12-04 02:21

    The + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed. The - is not overloaded in such a way and all operands are converted to numbers.

    From the specification:

    11.6.1 The Addition 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)

    8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).
    (...)

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

    0 讨论(0)
  • 1st: it casts 2nd operand to the 1st operand (String), because + is used for strings concat too.

    2nd: it casts 2nd operand to a Number, because - is just used for numbers operations.

    0 讨论(0)
  • 2020-12-04 02:24

    + is used for both concatenation and addition, but when used with a string, defaults to concatenation. - cannot be used on strings, so its operands are converted to numbers.

    Edit: This is not meant to be identical to the above post! XD

    0 讨论(0)
  • 2020-12-04 02:47

    + is used for both string concatenation and addition. If either operant is a string, concatenation is used. - is only used for subtraction, both operants are always cast to numbers.

    0 讨论(0)
提交回复
热议问题