2015-11-18 47 views
0

是否可以在Javascript中的開關塊內使用來自開關塊的響應使用if/else語句?以下是我的嘗試。這是一個CodeAcademy項目,您必須使用開關塊和條件語句對自己的冒險進行編碼。如果語句在開關塊中javascript

var user = prompt("You awake; dazed, blurred and lost. What do you do?").toLowerCase() 
var day = 0; 

switch (user) { 
    case "look at the time": 
     console.log("Good start, how long was I out for?"); 
     if (
     case "look at the time" && day === 0) { 
      console.log("it's only been a few hours, but time is still ticking"); 
      day++ 
     } else if (day > 0) { 
      console.log("it's been " + day + "s! Will I make it out of here"); 
      day++ 
     } 
     break; 
    case "figure out where I am": 
     console.log("Yeah, how did I end up here in the first place?"); 
     if (
     case "figure out where I am" && day === 0) { 
      console.log("This is a good checkpoint"); 
      day++ 
     } 
     break; 
    case 'run': 
     console.log("Dry your eyes, find a direction, and hope for the best"); 
     break; 
    case 'give up': 
     console.log('Thanks for trying, have fun, where ever you are...'); 
     break; 
    default: 
     console.log("you fall back unconscious, hoping to wake again"); 
     day++; 
     if (
     default) { 
      return user; 
     } 
     if (
     case 'run' || 
     case 'give up') { 
      console.log("It would have ended up coming down to this option anyway"); 
     } 
} 
+1

你不需要再次檢查(並且不能)'case',只需檢查一天。 – Teemu

+0

不,不能將if語句放在'switch'塊中。你只能在那裏放置'case'。而且你不能在'if'條件下放置'case's。這只是一個語法錯誤。 – Bergi

回答

0

,如果你做出改變,以停止使用if語句中的字case它將工作,例如,它應該是這樣執行的比較,從case語句的user變量:

if (user === "look at the time" && day === 0) { 
    console.log("it's only been a few hours, but time is still ticking"); 
    day++ 
} else if (day > 0) { 
    console.log("it's been " + day + "s! Will I make it out of here"); 
    day++ 
} 

在這種情況下,比較user === "look at the time"是多餘的,因爲該邏輯已經在switch語句本身中進行了評估。我只是將它包括在內,以便您可以看到如何與user變量進行比較,但可以將其完全排除,並且在此情況下具有相同的效果。