为什么这个函数调用两次?

时间:2014-10-23 19:58:00

标签: javascript function

JS的新手还在学习,但为学校写了一个计算器。我已经完成了很多工作并解决了所有问题,但是我遇到了一个小问题,我无法确定问题。任何帮助表示赞赏。一切正常,但回答"函数连续两次被调用。它第一次显示,一切都是正确的,但第二次它显示我的一个变量未定义。我显然只需要它第一次出现就好了。我错过了什么?

var number1;
var number2;
var operator;
var total;
var runagain;

function main()
{
    inputNumbers();
    assignment();
    answer();
    keepgoing();
}

function inputNumbers()
{
    number1 = parseInt(prompt("Enter Your First Number", 0));
    while(isNaN(number1))
    {
        alert("You did not enter a valid number. Please try again.");
        number1 = parseInt(prompt("Enter Your First Number", 0));
    }
    number2 = parseInt(prompt("Enter Your Second Number", 0));
    while(isNaN(number2))
    {
        alert("You did not enter a valid number. Please try again.");
        number2 = parseInt(prompt("Enter Your Second Number", 0));
    }
}

function assignment()
{
    operator = parseInt(prompt("Enter a '1' for addition\n" + "Enter a '2' for subtraction\n" + "Enter a '3' for multiplication\n" + "Enter a '4' for division\n" + "Enter a '5' for modulus/remainder"));

    if(operator == 1)
    {
        add();
        operator = " + ";
        answer(operator);
    }

    else if(operator == 2)
    {
        subtract();
        operator = " - ";
        answer(operator);   
    }
    else if(operator == 3)
    {
        multiply();
        operator = " * ";
        answer(operator);   
    }
    else if(operator == 4)
    {
        divide();
        operator = " / ";
        answer(operator);   
    }
    else if(operator == 5)
    {
        modulus();
        operator = " % ";
        answer(operator);   
    }
}

function add()
{
    total = number1 + number2;
}

function subtract()
{
    total = number1 - number2;
}

function multiply()
{
    total = number1 * number2;
}

function divide()
{
    total = number1 / number2;
}

function modulus()
{
    total = number1 % number2;
}

function answer(operator)
{
    alert("Your calculation was: " + number1 + operator + number2 + " = " + total);
}

function keepgoing()
{
    runagain = confirm("Would you like to make another calculation?");

    if(runagain === true)
    {
        main();
    }
}

3 个答案:

答案 0 :(得分:3)

您在此功能中调用answer():

function main()
{
inputNumbers();
assignment();
answer(); // <- here
keepgoing();
}

但你也打电话给assignment(),它会回复answer()函数:

function assignment()
{
    operator = parseInt(prompt("Enter a '1' for addition\n" + "Enter a '2' for subtraction\n" + "Enter a '3' for multiplication\n" + "Enter a '4' for division\n" + "Enter a '5' for modulus/remainder"));

    if(operator == 1)
    {
        add();
        operator = " + ";
        answer(operator); // <- here, and also in subsequents if/else blocks
    }

...

旁注:parseInt应始终与parseInt(x,10)参数一起使用,如果您要在十进制系统中进行解析。

答案 1 :(得分:2)

您只是简单地调用answer()函数两次。您不应该从main()中调用它,因为您的变量(operator)未定义。

答案 2 :(得分:0)

在定义运算符时,第一次从赋值函数调用

下次从函数调用时,其中未定义运算符

因此错误