2017-06-13 74 views
-4

我正在製作一個簡單的JS計算器。但是,變量中的提示不會出現。是的,我會將孩子的功能改變成變量,以使開關語句成爲可能。但即使將它打成JS固定器,它也不起作用。任何人都可以告訴我該怎麼做?我有點卡在這裏。我曾嘗試把它放入JSFiddle,但它仍然沒有奏效。謝謝,如果我得到答案!我的提示代碼不起作用

var firstNumber = prompt("Type in the first number that you want to add,subtract,divide,multiply,power(square or to the power of) or square root."); 

    var operationForNumber() = prompt("Type in the symbol that matches the operation that you want to use(2 for square, ! for square root, /,for division and a * for multiplication)."); 

    var secondNumber() = prompt("Type in the second number that you want to add,subtract,divide,multiply,square or square root."); 


    switch (operationForNumber) { 
     case +: 
      firstNumber "+" 
      secondNumber 
      break; 
     case -: 
      firstNumber "-" 
      secondNumber 
      break; 
     case /: 
     firstNumber "/" 
     secondNumber 
     case *: 
      firstNumber "*" 
      secondNumber 
      break; 
     case 2: 
      Math.pow(firstNumber, secondNumber); 
      break; 
     case !: 
      sqrt(firstNumber) 
     default: 
      console.log("The number you have typed is too great to be calculated or the operation that you chose(+,/,-,X) isn't valid!"); 
    } 
+1

用引號括起你的操作符,否則你有語法錯誤 – DarkBee

+0

運算符在+, - 等? – DudeManPerson

+0

您需要在環境中看到語法錯誤,因爲它們太多(缺少變量,不存在的函數等等) –

回答

1

您的代碼失敗,因爲您沒有在switch-cases中的運算符周圍引用引號。這樣做對所有的案件:

case "+": 
case "-": 

+0

這不是唯一的問題,「sqrt」也沒有定義,他使用operationForNumber作爲變量,即使它是一個函數,等等。 –

+0

this.lau - 我知道函數部分。上面已經提到過。我可以解決這個問題! – DudeManPerson

0

你必須存儲在變量提示符調用的結果,使它們可用於開關內的語句。

var firstNumber = prompt("Type in the first number that you want to add,subtract,divide,multiply,power(square or to the power of) or square root."); var operationForNumber = prompt("Type in the symbol that matches the operation that you want to use(2 for square, ! for square root, /,for division and a * for multiplication)."); var secondNumber = prompt("Type in the second number that you want to add, subtract, divide, multiply, square or square root."); 此外請堅持一致的代碼風格並用分號終止語句。