[英]The value returned for a newly constructed object returns the value of the previously created one
我在 javascript 中練習 OOP 有以下挑戰:
世行應允許我們:
添加客戶
所以我做了以下,我用不同的方法創建了一個 Bank class。
它似乎與一個人一起工作正常,但我的問題是,一旦我添加了一個新客戶,並在新客戶上運行這些方法,它就會返回第一個客戶的價值。
class Bank { constructor() { this.customers = []; } addCustomer(customer) { this.customers.push({ name: customer, account: 0 }); } printAccount(customer) { if (this.customers.some((person, idx) => person.name === customer)) { console.log( `${this.customers[0].name}'s account is ${this.customers[0].account}` ); } else { console.log("no access"); } } depositAmount(customer, amount) { if (this.customers.some(person => person.name === customer)) { this.customers[0].account += amount; } else { return; } } withdrawAmount(customer, amount) { if (this.customers.some(person => person.name === customer)) { this.customers[0].account -= amount; } else { return; } } } const bank = new Bank(); bank.addCustomer("daniel"); bank.depositAmount("daniel", 10); bank.withdrawAmount("daniel", 5); bank.printAccount("daniel"); bank.addCustomer("gwen"); bank.depositAmount("gwen", 10); bank.printAccount("gwen"); console.log(bank);
你總是在你的方法中使用this.customers[0]
,所以它總是對第一個客戶進行操作。
使用find()
找到客戶 object,並使用它。
class Bank { constructor() { this.customers = []; } addCustomer(customer) { this.customers.push({ name: customer, account: 0 }); } getCustomer(name) { return this.customers.find(person => person.name == name); } printAccount(name) { const customer = this.getCustomer(name); if (customer) { console.log( `${customer.name}'s account is ${customer.account}` ); } else { console.log("no access"); } } depositAmount(name, amount) { const customer = this.getCustomer(name); if (customer) { customer.account += amount; } } withdrawAmount(name, amount) { this.depositAmount(name, -amount); } } const bank = new Bank(); bank.addCustomer("daniel"); bank.depositAmount("daniel", 10); bank.withdrawAmount("daniel", 5); bank.printAccount("daniel"); bank.addCustomer("gwen"); bank.depositAmount("gwen", 10); bank.printAccount("gwen"); console.log(bank);
您應該改用find
:
depositAmount(customer, amount) {
const customer = this.customers.find((person) => person.name === customer);
if (!customer) return; // no customer exists
customer.account += amount; // add to customer
}
如果沒有找到客戶,它會返回undefined
,您可以檢查一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.