运行它时,出现“ TypeError:无法读取未定义的属性'balance'”。
我是初次接触Node的人,我不确定自己做错了什么。请帮忙。
它与范围有关吗?我应该如何解决?
//create an accounts array:
var accounts = [];
// create a function that allows you to create an account, passing it an account object:
function createAccount(account)
{
accounts.push(account);
return account;
}
// create a function that allows you to lookup an account by passing it a username:
function getAccount(userName)
{
var matchedAccount;
for (var i = 0; i < accounts.length; i++)
{
if (accounts[i] === userName)
{
matchedAccount = accounts[i];
}
}
return matchedAccount;
}
// create a function called deposit:
function deposit(account, amount)
{
if (typeof amount === "number")
{
account.balance = (account.balance + amount);
}
else
{
console.log("Deposit failed. Amount is not a number.")
}
}
// create a function called withdrawal:
function withdraw(account, amount)
{
if (typeof amount === "number")
{
account.balance = (account.balance - amount);
}
else
{
console.log("Withdraw failed. Amount is not a number.")
}
}
// create a function called getBalance, which will return the current balance of the account passed to it:
function getBalance(account)
{
return account.balance;
}
function createBalanceGetter(account)
{
return function()
{
return account.balance;
}
}
var jessica = createAccount(
{
userName: "Jessica",
balance: 0
});
deposit(jessica, 120);
withdraw(jessica, 10);
var jessica2 = getAccount("Jessica");
var getJessica2Balance = createBalanceGetter(jessica2);
console.log(getJessica2Balance());
最佳答案
在您的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与给定的用户名进行比较。之前,您将一个account对象与一个字符串进行比较,这是不正确的。这导致
createBalanceGetter
尝试访问undefined.balance
,这给出了错误。这是fiddle。