问题描述:

I'm creating a little calculator. Part of this will allow you to input upto 4 numbers but you could just have 1,2 or 3 as well. I've got the code working except for when I only enter 1, 2 or 3 numbers I get a NaN result for the numbers I haven't entered.

How do I get rid of the NaN result?

my jQuery for splitting the inputted form data is -

 var numbers = num4.split(" ");

var firstNumber = parseInt(margins[0], 10),

secondNumber = parseInt(margins[1], 10),

thirdNumber = parseInt(margins[2], 10),

fourthNumber = parseInt(margins[3], 10);

console.log(firstNumber, secondNumber, thirdNumber, fourthNumber);

var shorthand1 = parseInt (firstNumber, 10) * 1;

var shorthand2 = parseInt (secondNumber, 10) * 1;

var shorthand3 = parseInt (thirdNumber, 10) *1;

var shorthand4 = parseInt (fourthNumber, 10) *1;

and I just have

shorthand1 + shorthand2 + shorthand3 + shorthand4

as a result displayed in a div on the page.

The issues is if I enter "10 10 10" and not enter a fourth number I get a result of

10 10 10 NaN

Can I check for NaN and not get that result processed?

网友答案:

You can check if a value is NaN by using the Javascript isNaN(value) function.

网友答案:

You could check isNaN() in js.

Note that the isNaN() function only checks for the "numerical nature" of a value, not whether the value it is finite. To check if a number is finite, you should instead use JavaScript's isFinite().

网友答案:

The isNaN() function determines whether a value is an illegal number (Not-a-Number).

This function returns true if the value is NaN, and false if not.

<script type="text/javascript">
document.write(isNaN(123)+ "<br />");
document.write(isNaN("Hello")+ "<br />");
document.write(isNaN(NaN)+ "<br />");
</script> 

Output:
false
true true
For your case, you can check like below:

<html>
<body>
<script type="text/javascript">
if(!isNaN(123)){
document.write(isNaN(123)+ "<br />");
}
if(isNaN("Hello")){
document.write(isNaN("Hello")+ "<br />");
}
</script>
</body>
</html>
相关阅读:
Top