[英]JavaScript — How can I make a rule to make sure a user entered a value between two specific numbers
[英]How to add numbers entered by user in Javascript
以下是我为了尝试添加用户输入的两个数字而执行的JavaScript,但是我得到的结果是“ NaN”:
<HTML>
<HEAD>
<TITLE>JavaScript-Functions</TITLE>
</HEAD>
<BODY>
<H1>JavaScript-Functions</H1>
<P>This function will add two numbers.</P>
<script type="text/JavaScript">
<!-- This is a math function -->
var x = prompt("Please enter the first number: ");
var y = prompt("Please enter the second number: ");
function addTwo(x, y)
{
var xNum;
xNum = parseInt(x);
var yNum;
yNum = parseInt(y);
return xNum + yNum;
}
document.write(addTwo(x, y));
</script>
</BODY>
</HTML>
这里的一切看起来不错,除了html注释
<!-- This is a math function -->
在脚本标记中。
如果您提供数字作为输入,则表示它一定可以工作,否则会抛出错误“ NaN”。
尝试使用回调。 这是由于javascript的异步事件I / O模型。
var x = prompt("Please enter the first number: ");
var y = prompt("Please enter the second number: ");
function addTwo(x, y, callback){
var xNum;
xNum = parseInt(x);
var yNum;
yNum = parseInt(y);
var result = xNum + yNum;
callback(result);
}
addTwo(x, y, function(result){
document.write(result);
});
CODEPEN编辑:链接
您可以摆脱parseInt()
的位置,并在提示符前加上一个+
。 这将解析提示响应并将其从字符串更改为整数。
<script type="text/JavaScript">
<!-- This is a math function -->
var x = +prompt("Please enter the first number: ");
var y = +prompt("Please enter the second number: ");
document.write(x, y);
</script>
就这样 因此,iv算出了+
号可以完成的三件事:1.连接字符串和变量2.放在窗口对象前面时,就像parseInt()
3.和它通常的函数一样,添加整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.