2016-09-06 96 views
2

當我運行它時,我得到「TypeError:無法讀取未定義的屬性'平衡'。」 我剛剛學習Node,我不確定自己做錯了什麼。請幫忙。「TypeError:無法讀取未定義的屬性'balance'」。不知道什麼是錯的

它與範圍有關嗎?我應該如何解決它?

//create an accounts array: 
 
var accounts = []; 
 

 
// create a function that allows you to create an account, passing it an account object: 
 
function createAccount(account) 
 
{ 
 
\t accounts.push(account); 
 
\t return account; 
 
} 
 

 
// create a function that allows you to lookup an account by passing it a username: 
 
function getAccount(userName) 
 
{ 
 
\t var matchedAccount; 
 

 
\t for (var i = 0; i < accounts.length; i++) 
 
\t { 
 
\t \t if (accounts[i] === userName) 
 
\t \t { 
 
\t \t \t matchedAccount = accounts[i]; 
 
\t \t } 
 
\t } 
 
\t 
 
\t return matchedAccount; 
 
} 
 

 
// create a function called deposit: 
 
function deposit(account, amount) 
 
{ 
 
\t if (typeof amount === "number") 
 
\t { 
 
\t \t account.balance = (account.balance + amount); 
 
\t } \t 
 
\t else 
 
\t { 
 
\t \t console.log("Deposit failed. Amount is not a number.") 
 
\t } 
 
} 
 
    
 
// create a function called withdrawal: 
 
function withdraw(account, amount) 
 
{ 
 
\t if (typeof amount === "number") 
 
\t { 
 
\t \t account.balance = (account.balance - amount); 
 
\t } \t 
 
\t else 
 
\t { 
 
\t \t console.log("Withdraw failed. Amount is not a number.") 
 
\t } 
 
} 
 
    
 
// create a function called getBalance, which will return the current balance of the account passed to it: 
 
function getBalance(account) 
 
{ 
 
\t return account.balance; 
 
} 
 
    
 
function createBalanceGetter(account) 
 
{ 
 
\t return function() 
 
\t { 
 
\t \t return account.balance; 
 
\t } 
 
} 
 
    
 
var jessica = createAccount(
 
{ 
 
\t userName: "Jessica", 
 
\t balance: 0 
 
}); 
 
    
 
deposit(jessica, 120); 
 
withdraw(jessica, 10); 
 

 
var jessica2 = getAccount("Jessica"); 
 
var getJessica2Balance = createBalanceGetter(jessica2); 
 

 
console.log(getJessica2Balance()); 
 

 

回答

2

在你getAccount,你必須尋找accounts[i].userName,不只是accounts[i]。更改getAccount功能如下:

function getAccount(userName) 
{ 
    var matchedAccount; 

    for (var i = 0; i < accounts.length; i++) 
    { 
     if (accounts[i].userName === userName) 
     { 
      matchedAccount = accounts[i]; 
     } 
    } 

    return matchedAccount; 
} 

現在,這確實對每個帳戶線性搜索,且該帳戶的的userName比較給定的用戶名。在此之前,您是在將帳戶對象與字符串進行比較,這是不正確的。這導致createBalanceGetter嘗試訪問undefined.balance,從而導致該錯誤。這是一個fiddle

+0

這絕對是問題!我一直試圖找出幾個小時有什麼問題。 **非常感謝你!** _(我不能upvote你的答案,因爲我有不到15的聲譽...我試過。)_ – Jess

+0

沒問題@Jess很高興我幫了忙! – Li357

相關問題