“TypeError:无法读取未定义的属性”余额“。 不知道什么是错的

当我运行它,我得到“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()); 

       

网上收集的解决方案 "“TypeError:无法读取未定义的属性”余额“。 不知道什么是错的"

在您的getAccount ,您必须searchaccounts[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; } 

现在,它会对每个帐户进行线性search,并将帐户的用户名与给定的用户名进行比较。 在此之前,您正在将帐户对象与string进行比较,这是不正确的。 这导致createBalanceGetter尝试访问undefined.balance ,从而导致错误。 这是一个小提琴 。