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());
這絕對是問題!我一直試圖找出幾個小時有什麼問題。 **非常感謝你!** _(我不能upvote你的答案,因爲我有不到15的聲譽...我試過。)_ – Jess
沒問題@Jess很高興我幫了忙! – Li357