Javascript counter variable not incrementing only appending digits [duplicate]

有些话、适合烂在心里 提交于 2019-12-25 02:44:29

问题


  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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!