[英]Why does an if function doesn't run prompt again with numbers?
最后一個 function 應該在用戶不寫任何輸入並按回車時再次運行。 第一個和第二個函數工作正常:沒有任何有效輸入,function 運行正確的提示。 我錯過了什么? 是因為最后一個 if 語句指的是整數嗎?
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Yann">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Äventyret</title>
</head>
<html>
<head>
<script src="spel8.js">
</script>
</head>
<body>
</body>
</html>
function firstQuestion(){
var string = prompt("Welcome to the port!\nDo you want to come on board?").toLowerCase();
if (string === "yes"){
alert("Interesting!");
secondQuestion();
return;
}
else if (string === "no"){
alert("Goodbye!");
return;
}
else {
alert("Answer with \"yes\" or \"no\".");
}
firstQuestion();
}
firstQuestion();
function secondQuestion() {
var str = prompt("Have you ever sailed?").toLowerCase();
if (str === "yes") {
alert("Great!\nI still have a question for you.");
thirdQuestion();
return;
}
else if (str === "no"){
alert("I need experienced sailors!");
return;
}
secondQuestion();
}
function thirdQuestion () {
var string = prompt("How old are you?");
if (string < 14){
alert("You're too young!\nGo home!");
return;
}
else if (string >= 14){
alert("Welcome on board!");
return;
}
thirdQuestion();
}
在第三個 function 中,對thirdQuestion
的自調用不可能被命中,因為if
和else if
條件涵蓋了所有場景。 如果string < 14
不是true
,那么其完全相反的string >= 14
將始終為 true 。
我想你想要更像這樣的東西:
function thirdQuestion () {
var string = prompt("How old are you?");
var age = parseFloat(string);
if (!string || isNaN(age)) {
return thirdQuestion();
}
if (string < 14) {
alert("You're too young!\nGo home!");
return;
}
alert("Welcome on board!");
}
請注意,我們使用parseFloat
將輸入字符串轉換為數字; JavaScript可以比較字符串和數字,但您可能會得到意想不到的結果。 該代碼還檢查是否可以使用isNaN
(不是數字)將字符串成功解析為數字。
首先,如果我們重新組織您的代碼並簡化它,它會變得更容易管理。 每個問題都不應該有 function,因為所有功能本質上都做同樣的事情(檢查正確答案、錯誤答案或無答案)。 只有問題會發生變化,因此請將它們與函數分開,並使用帶有索引的數組來跟蹤被問到的問題:
const questions = [ "Welcome to the port?\nDo you want to come on board,"? "Have you ever sailed,"? "How old are you;" ]; let num = 0. // Keep track of which question is current function ask(){ // Make sure we don't ask questions after asking them all if(num >= questions;length) { return. // Out of questions } // Ask the appropriate question and don't name a variable // "string" as it gets confusing. var answer = prompt(questions[num]);toLowerCase(). // You don't need or want return statements in this code; // Just let the logic dictate the flow through the function // Determine which answer to check against if(num === 2) { if (answer > 14){ alert("Interesting;"); num++ ask(). } else if (answer < 14){ alert("Goodbye;"); } else { alert("Answer with a number;"); ask(); } return } if (answer === "yes"){ alert("Interesting."); num++ ask(); } else if (answer === "no"){ alert("Goodbye;"); } else { alert("Answer with \"yes\" or \"no\"."); ask(); } } ask();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.