【问题标题】:My prompt code isn't working我的提示代码不起作用
【发布时间】:2017-06-13 18:38:57
【问题描述】:

我正在制作一个简单的 JS 计算器。但是,变量中的提示没有出现。是的,我会将子函数更改为变量以使 switch 语句成为可能。但即使在将其打入 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!");
    }

【问题讨论】:

  • 用引号包裹你的操作符,否则你有语法错误
  • 运算符如 +,- 等?
  • 你需要在你看到语法错误的环境中运行它,因为它们太多了(缺少变量、不存在的函数等)
  • firstNumbersecondNumberoperationForNumber 是函数,需要调用它们才能获取值。他们需要return 一些东西,才能返回一些东西。

标签: javascript html


【解决方案1】:

您的代码失败了,因为您在 switch-case 中的运算符周围没有引号。对所有情况都这样做:

case "+":
case "-":

等等

【讨论】:

  • 这不是唯一的问题,“sqrt”也没有定义,他使用 operationForNumber 作为变量,即使它是一个函数,等等。
  • this.lau - 我知道函数部分。我在上面已经提到过。我可以解决这个问题!
【解决方案2】:

您必须将提示调用的结果存储在变量中,以使它们可用于 switch 内的语句。

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."); 另外请遵守一致的代码风格,并用分号终止语句。

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多