JavaScript 添加整数
如何在 Javascript 中将一个简单整数添加到另一个整数?
我得到 NaN 作为总计值。
<script type="text/javascript">
var total = 0;
document.getElementById("dds1").onkeyup = function() {
total = total + parseInt(this.value,10);
updateIt();
};
function updateIt() {
//tofixed(2)
document.getElementById("mySpan").innerHTML = total;
}
但如果我执行以下操作:
total = parseInt(this.value,10);
那么总计就有一个值(整数值)。
How do I add a simple integer to another integer in Javascript?
I'm getting NaN as the value for total.
<script type="text/javascript">
var total = 0;
document.getElementById("dds1").onkeyup = function() {
total = total + parseInt(this.value,10);
updateIt();
};
function updateIt() {
//tofixed(2)
document.getElementById("mySpan").innerHTML = total;
}
But if I do the following:
total = parseInt(this.value,10);
then total has a value (an integer value).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您
执行加法在每次按键时读取输入值。例如,如果用户按 BACKSPACE 清除输入,则该值将是一个空字符串,这将在 parseInt 后导致 NaN。一旦你有了 NaN(在你的total
变量中),你就无法再摆脱它了。试试这个:
在这里,您首先检查输入值是否可以解析为数字。如果没有,你就直接无视它。
另一种方法是这样的:
在这里,如果您读取无法转换为数字的输入值,则只需完全返回该函数即可。
The problem is that you
execute the additionread the input value on every keyup. If the user, for instance, presses BACKSPACE to clear the input, the value will be an empty string, which will result in NaN after parseInt. And once you have NaN (in yourtotal
variable), you cannot get rid of it anymore.Try this:
Here, you first check if the input value can be parsed as a number. If not, you just disregard it.
Another way of doing it would be this:
Here, if you read an input value that cannot be converted into an number, you just return the function altogether.
这是用于添加整数的 javascript。
好处是,即使是空格,它也不会抛出任何错误。
JavaScript
引用自:http://www. ittutorials.in/source/javascript/scf4/addition-of-multiple-integers-using-javascript.aspx
Here is the javascript to add integers.
Good thing is that it won't throw any error even for blank spaces.
Javascript
Referred from : http://www.ittutorials.in/source/javascript/scf4/addition-of-multiple-integers-using-javascript.aspx