Add two variables using jquery

前端 未结 6 1906
青春惊慌失措
青春惊慌失措 2020-12-07 16:18
var a = 1;
var b = 2;
var c = a+b;

c will show as 12; but I need 3

How do I do it using jQuery?

6条回答
  •  没有蜡笔的小新
    2020-12-07 16:40

    It looks like you have strings and not numbers, you need parseInt() or parseFloat() (if they may be decimals) here, like this:

    var a = "1";
    var b = "2";
    var c = parseInt(a, 10) + parseInt(b, 10);
    //or: var c = parseFloat(a) + parseFloat(b);
    

    You can test the difference here, it's worth noting these are not jQuery but base JavaScript functions, so this isn't dependent on the jQuery library in any way.

提交回复
热议问题