" TypeError:无法读取属性' balance'未定义"。不确定有什么问题

时间:2016-09-06 01:19:49

标签: javascript node.js

当我运行它时,我得到" TypeError:无法读取属性'平衡'未定义的。" 我是学习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());

 
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

,您必须搜索getAccount,而不仅仅是accounts[i].userName。将accounts[i]功能更改为:

getAccount

现在,这会对每个帐户进行线性搜索,并将帐户的 userName 与给定的用户名进行比较。之前,您将帐户对象与字符串进行比较,这是不正确的。这导致function getAccount(userName) { var matchedAccount; for (var i = 0; i < accounts.length; i++) { if (accounts[i].userName === userName) { matchedAccount = accounts[i]; } } return matchedAccount; } 尝试访问createBalanceGetter,这会产生错误。这是fiddle