2014-10-03 99 views
0

我在代码顶部有两个函数。在下面的while (i<1)循环中,我称之为上述函数之一。此作品是第一次,但功能被称之为第二次显示错误:调用循环中的函数,“未定义不是函数”

TypeError: undefined is not a function

下面是代码:

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; 
     } 
    } 
} 
+0

我衷心希望这不是一个真正的金融交易.... – briansol 2014-10-03 13:58:11

回答

1

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

若要解决此问题,请修改您的功能,以便它们可以而不是newBalance转换为字符串。您应该使用toFixed只有当你显示的平衡:

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