How to concatenate two numbers in javascript?

后端 未结 16 2396
傲寒
傲寒 2020-12-13 16:33

I\'d like for something like 5 + 6 to return \"56\" instead of 11.

16条回答
  •  自闭症患者
    2020-12-13 17:22

    To add to all answers above I want the share the background logic:

    Plus is an addition operator that is also used for concatenation of strings. When we want to concatenate numbers. It should be the understanding that we want to concatenate the strings, as the concatenation of numbers doesn't make valid use cases to me.

    We can achieve it in multiple ways,

    Through type conversion

    let a = 5;
    a.toString()+5 // Output 55 type "string"
    

    This will also work and doing type conversion in the background,

    5 +""+ 5 // Output 55 type "string"
    

    If you are determined to concatenate two string and type of output should be int, parseInt() works here

    parseInt(5 +""+ 5)  //Output 55 Type "number"
    

提交回复
热议问题