Hello I just have a syntax question,
I have this test app
adding gold every 2 seconds.
And when app start it retrieves gold on server like so.
this.gold = this.gold3+this.rubix.gold,
but problem is instead of adding numbers the code decide to
add them like 2+2=22
and after a while its upin several 1000.
both are objects by the way cause server value must be saved like an object
is there any way to fix this?
Assuming you got it from a server, it’s probably a String
. You have to convert it to a number first. Try parseInt
(or parseFloat
if the number can have decimal places).
As @n-kartha says, it’s because you’re using +
with strings, so you are joining strings rather than adding numbers.
> 2 + 1
3
> 2 + '1'
'21'
> '2' + 1
'21'
> '2' + '1'
'21'
parseInt
is useful, but verbose and there are caveats to using it:
> parseInt('2') + parseInt('1')
3
> parseInt('2') + parseInt('0xf')
17
The caveat is that you need to provide a radix, otherwise you may get strange results (eg JS may assume the number is not base-10)
> parseInt('2', 10) + parseInt('1', 10)
3
> parseInt('2', 10) + parseInt('0xf', 10)
NaN
So if the values you have saved are definitely going to be (base-10) numbers, you can use the Number
function:
> Number('2') + Number('1')
3
Or you can use the unary plus operator to do the same thing:
> +'1'
1
> +'2'
2
> +'1' + +'2'
3
> var foo = '10'
> var bar = '20'
> +foo + +bar
30
Did not know that the unary +
did that . Thanks for showing it to me!
thanks I think this fix works. one of the data was a string so i try parse int it
i will see if this works )