![](/img/trans.png)
[英]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.