在循环中调用函数,“未定义不是函数”

时间:2014-10-03 13:52:43

标签: javascript function

我的代码顶部有两个函数。在while (i<1)循环下面,我调用上面的函数之一。这是第一次工作,但第二次调用该函数时会显示错误:

  

TypeError:undefined不是函数

以下是代码:

var i = 0;
var newBalance = 0;
var deposit = function(amountIn)
{
    newBalance = (newBalance + amountIn).toFixed(2);
};
var withdrawl = function(amountOut)
{
    newBalance = (newBalance - amountOut).toFixed(2);
};
var choice = prompt("Would you like to access your account?").toLowerCase();
if (choice === "yes"){
    while (i<1){

        var inOrOut = prompt("Are you making a deposit or a withdrawl?").toLowerCase();
        var strAmount = prompt("How much money are you trasfering?");
        var amount = parseFloat(strAmount);

        if (inOrOut === "deposit")
        {
            deposit(amount);
        }
        else if (inOrOut === "withdrawl")
        {
            withdrawl(amount);
        }
        else
        {
            console.log("You did not enter a valid number");
        }

        console.log("Your new balance is $" + newBalance);
        var choiceTwo = prompt("Would you like to make another transaction?").toLowerCase();
        if (choiceTwo === "no")
        {
            i = i + 1;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

最初,您将newBalance设置为一个数字。但是,调用任一函数会将newBalance设置为字符串。 (toFixed返回一个字符串,而不是一个数字。)之后,newBalance + amountIn也将是一个字符串(并且与您想要的完全不同)+将表示字符串连接而不是另外),所以它没有toFixed方法。所以你得到了你看到的错误。

要解决此问题,请修改您的功能,以便他们newBalance转换为字符串。只有在显示余额时才应使用toFixed

console.log("Your new balance is $" + newBalance.toFixed(2));