我想在我的代碼中限制符號,負數和所有其他非相對的東西。我的教授告訴我使用isNaN,但我不知道如何在我的代碼中應用。有人可以幫我解決這個問題嗎?我重視我的代碼如下
如何使用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>
'isNaN(其他)'爲真,如果'whatever'不一個數字 - 注意:即使'1.23「是一個字符串,isNaN(」1.23「)將是假的 - 所以如果你想像這樣使用它們,你仍然需要將值解析/強制爲'Number' –