2017-06-13 100 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."); 此外请坚持一致的代码风格并用分号终止语句。