Javascript addition and subtraction with a string value

前端 未结 8 1127
猫巷女王i
猫巷女王i 2021-01-20 04:31

I recently went through this typecast JS question:

Given \'11\'+10, the answer is 1110. It is clear that is not 21 because one

8条回答
  •  我在风中等你
    2021-01-20 05:00

    + sign is used for both Number and String concatenate. So it considers as two string concatenate when it found string first. You can use + prefix or Number to convert string to number

    But - sign is used for subtraction only applicable to number. So it automatically converts string to number.

    Following will solve your issue

    (+'11') + 10
    (+'11') - 10
    
    (or)
    
     Number('11') + 10
     Number('11') - 10
    

提交回复
热议问题