我想在我的代码中限制符号,负数和所有其他非相关内容。我的教授告诉我使用isNaN,但我不知道如何在我的代码中应用。有人可以帮我解决这个问题吗?我在下面附上了我的代码
<!-- Network Latency Calculator -->
<html>
<head>
<meta charset = "utf-8">
<title>Network Latency Calculation</title>
<script>
var firstNumber; // first string entered by user
var secondNumber; // second string entered by user
var thirdNumber; // third string entered by user
var fourthNumber; // fourth string entered by user
var number1; // first number to add
var number2; // second number to add
var number3; // third number to add
var number4; // fourth number to add
var sum; // sum of number1 and number2 and number3 and number4
var sumresult;
// read in first number from user as a string
firstNumber = window.prompt( "Enter the Propagation time (no negative number, letter, blank space, and symbol is not allow)" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter the Transmission time (no negative number, letter, blank space, and symbol is not allow)" );
// read in third number from user as a string
thirdNumber = window.prompt( "Enter the Queuing time (no negative number, letter, blank space, and symbol is not allow)" );
// read in fourth number from user as a string
fourthNumber = window.prompt( "Enter the Propagation delay (no negative number, letter, blank space, and symbol is not allow)" );
// convert numbers from strings to integers
number1 = parseFloat( firstNumber );
number2 = parseFloat( secondNumber );
number3 = parseFloat( thirdNumber );
number4 = parseFloat( fourthNumber );
sum = number1 + number2 + number3 + number4; // add the numbers
sumresult = parseFloat( sum );
// display the results
document.writeln( "<h1>The network latency is " + sum + "</h1>" );
document.writeln( "<p>Propagation time " + number1 + "</p>" );
document.writeln( "<p>Transmission time " + number2 + "</p>" );
document.writeln( "<p>Queuing time " + number3 + "</p>" );
document.writeln( "<p>Propagation delay " + number4 + "</p>" );
if ( sumresult < 1 )
document.writeln( "<p>Network performance is good.</p>" );
else ( document.writeln( "<p>Warning: Network performance needs improvement.</p>" ));
</script>
</head><body></body>
答案 0 :(得分:0)
在生产网络应用程序中,您不会提示用户输入数字 - 您将显示一个表格供用户填写。
但是,由于我们正在使用玩具应用程序,您只需重复提示,直到用户正确使用:
function getNumberFromUser(promptText) {
var n = NaN;
while(isNaN(n) || (n < 0)) {
var nString = window.prompt(promptText);
n = parseFloat(nString);
}
return n;
}
var number1 = getNumberFromUser("Enter the Propagation time (no negative number, letter, blank space, and symbol is not allow)");
var number2 = getNumberFromUser("Enter the Transmission time (no negative number, letter, blank space, and symbol is not allow)");
//etc