如何在Javascript中添加用户输入的数字

How to add numbers entered by user in Javascript

本文关键字:用户 输入 数字 添加 Javascript      更新时间:2023-09-26

下面是我为了尝试添加用户输入的两个数字而做的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() s并在提示符前面放置+。这将解析提示响应并将其从字符串更改为整数。

<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>

就像那样。所以我数了三件+符号可以做的事情:1. 连接字符串和变量2. 当放置在窗口对象前面时,它就像parseInt()3.和它通常的功能,添加整数