+ 2
JavaScript confusion
Take a look at my codes, code called "Geometric Calculator [in progress]". I have the first function in JavaScript causing the problem. part of the function is: if(perimeterChecked()){ var result = 2 * (length + width); }else{ var result = length * width; } It checks if a check box is checked (works fine), but the calculation is messed up. I tried changing the calculation to length + width, and I realized it is being treated like a string. Why, and how can I fix that?
8 ответов
+ 22
if(perimeterChecked()){
var result = 2 * (Number(length) + Number(width));
}else{
var result = length * width;
}
+ 3
well if your data is coming from an input, then it's systematically gonna be a string (even if it includes numbers only).
+ 1
the + sign is also used for concatenation. if your variable are string, then JavaScript will perform a concatenation instead of an addition. to overcome this, you will have to convert your string to an integer.
So if your string only contains numbers, you can use the unary + operator.
ex +"10" + +"69"
In your case, it would give something like that: +length + +width
+ 1
KINGODX that's the answer I needed!! thanks! so it's string even if the input type is only number... okay :D
0
Yeah, but why is it treated like a String? I mean it works if I do 2*(length*width), but if I put a plus sign, it gives me weird results... is it something with the plus sign??
0
I know Java, I know HTML, and I don't need PHP for JavaScript. I was asking if you know what the cause is..
0
KINGODX okay, but my expression doesn't contain ANY strings. So why is it doing that?
- 4
to understand java script.. must study HTML,php, and java