问题
var counter = 0;
var userAdd = prompt("How many would you like to add?");
counter += userAdd;
console.log(counter);
New to javascript.
I am trying to get the counter to increment up by the amount that the userAdd variable specifies.
When I run this code all I get from the console.log() is, for example:
If userAdd is '1' each time:
01
011
0111
...etc.
instead of:
1
2
3
Whats the problem here?
回答1:
You need to type your result as an int rather than a string.
var userAdd = parseInt(prompt("How many would you like to add?"));
This forces the numeric adding instead of the string appending.
来源:https://stackoverflow.com/questions/31061920/javascript-counter-variable-not-incrementing-only-appending-digits