- 通过名称“deleteProductByName”删除产品的方法不起作用
- 返回所有已创建产品名称的方法“getAllProductNames”不起作用
- 返回所有产品总成本的方法“gettotalProductsPrice”,它应该充当“getter” 请帮忙修复这些方法
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
class Shop extends Product {
constructor(products) {
super();
this.products = [];
}
addProduct(newProduct) {
this.products.push(newProduct);
}
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName in this.products[i]) {
this.products.splice(i, 1);
}
}
}
getAllProductNames() {
return this.products.map(object => Object.values(object)[0].name);
}
get totalProductsPrice() {
return this.products.map(object => Object.values(object)[0].price).
reduce((p, c) => p + c);
}
}
const shop = new Shop();
shop.addProduct(new Product("product 1", 1, 200));
shop.addProduct(new Product("product 1", 1, 500));
shop.addProduct(new Product("product 2", 2, 1000));
console.log(shop.totalProductsPrice);
console.log(shop.getAllProductNames());
shop.deleteProductByName("product 2");
console.log(shop.products);
最佳答案
一般来说,您的脚本无法运行的原因主要是由于您对如何处理数组感到困惑。请注意,您的 this.products
是对象数组。一一回答您的问题:
问题1:通过名称“deleteProductByName”删除产品不起作用
这是因为您正在用逻辑检查键(而不是值):
productName in this.products[i]
你应该做的是使用它:
productName === this.products[i].name
问题2:返回所有已创建产品的名称“getAllProductNames”的方法不起作用
这是因为谓词/回调中的object
实际上指的是单个product
对象。该对象定义了 name
、count
和 price
。因此,不要做你所做的事情:
return this.products.map(object => Object.values(object)[0].name);
...使用它就可以了(只需使用点符号访问产品的属性/ key ):
return this.products.map(product => product.name);
Q3:返回所有产品总成本的方法“gettotalProductsPrice”应该充当“getter”
它被正确地定义为 setter/getter ,但您犯了与问题 2 中详述的相同错误:您没有正确访问价格。而不是这样做:
return this.products.map(object => Object.values(object)[0].price).reduce((p, c) => p + c);
...你应该这样做:
return this.products.map(product => product.price).reduce((p, c) => p + c);
<小时/>
查看概念验证示例:
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
class Shop extends Product {
constructor(products) {
super();
this.products = [];
}
addProduct(newProduct) {
this.products.push(newProduct);
}
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
getAllProductNames() {
return this.products.map(product => product.name);
}
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
}
const shop = new Shop();
shop.addProduct(new Product("product 1", 1, 200));
shop.addProduct(new Product("product 1", 1, 500));
shop.addProduct(new Product("product 2", 2, 1000));
console.log(shop.totalProductsPrice);
console.log(shop.getAllProductNames());
shop.deleteProductByName("product 2");
console.log(shop.products);
关于javascript - 为什么我处理数组的方法在 ECMA6 的类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50669392/