JavaScript adding a string to a number

后端 未结 8 613
轮回少年
轮回少年 2020-11-29 04:12

I was reading the re-introduction to JavaScript on MDN and in the section Numbers it said that you can convert a string to a number simply by adding a plus operator

相关标签:
8条回答
  • 2020-11-29 04:43

    You could also use parseInt() or parseFloat(), like this:

    > 1 + 2 + "3"
    "33"
    > 1 + 2 + parseInt(3)
    6
    

    I think that's alot cleaner than using +"3", but that is just my opinion.

    0 讨论(0)
  • 2020-11-29 04:47

    In the example of 3 + 4 + "5" - the Javascript parser will do (3+4)+"5", as the 3+4 is first - so it will add 3 + 4 because they are numbers, then concatenate the string "5".

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