2017-07-26 42 views
2

我試圖在JavaScript中的文字冒險遊戲初學者,我需要直到用戶輸入一個有效的答案重複switch語句:重複switch語句,直到它有一個有效的答案

opts = prompt("Do you want to TALK or LOOK?").toUpperCase(); 
 

 
switch(opts) { 
 
    case "TALK": 
 
    mes = "Is anyone in charge here?"; 
 
    speech = "Our leader is in the big building."; 
 
    talkNot(); 
 
    break; 
 
    case "LOOK": 
 
    window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street."); 
 
    break; 
 
    default: 
 
    window.alert("That's not an option."); 
 
}

任何答案會超級有幫助 - 謝謝!

+0

對於案例:看看,默認你的邏輯是好的,對談話我猜你已經定義talkNot(),有什麼問題嗎? –

回答

5

總結了一些函數的代碼和callback在默認聲明功能

function run(){ 
 
opts = prompt("Do you want to TALK or LOOK?").toUpperCase(); 
 

 
switch(opts) { 
 
    case "TALK": 
 
    mes = "Is anyone in charge here?"; 
 
    speech = "Our leader is in the big building."; 
 
    console.log('talk') 
 
    //talkNot(); 
 
    break; 
 
    case "LOOK": 
 
    window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street."); 
 
    break; 
 
    default: 
 
    window.alert("That's not an option."); 
 
    run() //callback 
 
} 
 
} 
 

 
run()

1

您可以使用一個簡單的do ... while結構。

let next = false 
 
do { 
 
    let opt = prompt("Do you want to TALK or LOOK?").toUpperCase(); 
 
    next = false 
 
    switch (opt) { 
 
    case 'TALK': 
 
    case 'LOOK': 
 
     break; 
 
    default: 
 
     next = true 
 
    } 
 
} while (next)