javascript Javascript将+1添加到字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33503111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript add +1 to string
提问by htmlcoder123
I have a variable that stores a innerHTML text in it
我有一个变量在其中存储了一个innerHTML文本
var text = document.getElementById("textID").innerHTML; // <-- textID is actually a number
The "text" is actually just a number but I guess javascript still thinks it's a string.
“文本”实际上只是一个数字,但我猜 javascript 仍然认为它是一个字符串。
I want to add + 1 to the variable text, but it just adds a new letter instead of increasing the number
我想在变量文本中添加 + 1,但它只是添加了一个新字母而不是增加数字
For example : 0 + 1 = 01 --> 01 + 1 = 011 and so on...
例如:0 + 1 = 01 --> 01 + 1 = 011 等等...
Here's the code I tried this with:
这是我尝试过的代码:
text = text + 1;
How can I make it so it increases the number instead of adding new letters? (1+1 = 2, etc)
我怎样才能使它增加数字而不是添加新字母?(1+1 = 2,以此类推)
回答by Griffith
Under the assumption that you are absolutely sure that the number is a decimal integer. Either
假设您绝对确定该数字是十进制整数。任何一个
text = +text + 1;
Or
或者
text = parseInt(text, 10) + 1;
Or
或者
text = Number(text) + 1;