2014-10-03 70 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));