简体   繁体   中英

How to add numbers entered by user in Javascript

The following is the JavaScript I did in order to try to add two numbers entered by the user but the result I'm getting is "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>

Everything looks good here, except the html comment

<!-- This is a math function -->

in script tag.

如果您提供数字作为输入,则表示它一定可以工作,否则会抛出错误“ NaN”。

try to use callback. This is due to the asynchronous evented I/O model of javascript.

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 EDITED:link

You could get rid of the parseInt() s and put a + in front of the prompt. That will parse the prompt response and change it from a string to an integer.

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

Just like that. So iv'e counted three things the + sign can do: 1. Concatenate strings and variables 2. It's like a parseInt() when placed in front of a window object 3. and its usual function, to add integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM