JavaScript adding a string to a number

后端 未结 8 782
轮回少年
轮回少年 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:30

    A smple + operator in javascript is used for concatenation and not to add.

    A bracket and a + operator before the string format integer variable will do the job every time.

    This always works fine.

    1 + (+"2") = 3
    

    Because placing + before string converts the string variable into number.

    fiddle here: http://jsfiddle.net/xuVur/2/

提交回复
热议问题