开发者

JS Vars - Adding

开发者 https://www.devze.com 2022-12-10 01:35 出处:网络
I have two variables, \'a\' and \'b\' in my JavaScript, and i want to add them together - i 开发者_如何学运维assume this code:

I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i 开发者_如何学运维assume this code:

var a = 10;
var b = 30
var varible = a + b;

This, puts the two numbers next to each other... any ideas why... the result should be 40?


You probably have strings instead of integers. That is your code really is like this:

var a = "10";
var b = "30";
var c = a + b; // "1030"

There are several ways to convert the strings to integers:

a = parseInt(a, 10);  // Parse the string
b = b * 1;            // Force interpretation as number


new is a reserved word, I'd use something else in any case.

And with a normal variable name of c it worked for me:

var a = 10;
var b = 30
var c = a + b;
alert(c);

did the expected and alerted 40


new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else


Are you sure you didn't do this:

var a = '30';
var b = '40';

Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:

var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );

If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:

<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;
</script>

Here, the value of a text input is always a string initially.

If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.


I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).

var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again

a + b; // "11"
b + a; // 2
a + c; // "11"

Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.


One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:

var newValue = parseInt(a,10) + parseInt(b,10);

Also, 'new' is a keyword. You can't use that for a variable name :)

0

精彩评论

暂无评论...
验证码 换一张
取 消