这个问题在这里已有答案:
我到处都是未定义的值,非常烦人。我相信这可能是我用const设置输入的方式的问题
const prod = new Product();
prod
或者是别的什么 ?我相信已经尝试修复一些功能,比如将此产品退回购买产品并使用null修复我的toLowerCase。
var products = [];
class Product {
constructor(productName, amount, cost) {
this.productName = productName,
this.amount = amount,
this.cost = cost
}
buyProduct(product){
products.push(product);
return this;
}
deleteProduct(str){
var found = products.find(function(element){
})
if(found)
{
if(found.amount>1)
}
}
}
您没有从所有方法返回this
,因此您无法链接所有方法。
sumPrice()
仅返回此项deleteProduct()
不归还这个sumTotal()
都没有此外,您的代码严重破坏。这是一个列表,我做了一些修复工作:
amount
和quantity
使用相同的属性名称item
和productName
使用相同的属性名称amount
和cost
使用数字而不是字符串let/const
而不是var
我还将Product
类的名称更改为ProductsStore
,因为您的类管理所有产品而不仅仅是一个,所以我在类中移动了products[]
数组并在构造函数中初始化它。
class ProductsStore {
constructor() {
this.products = [];
}
buyProduct(product) {
this.products.push(product);
return this;
}
deleteProduct(str) {
const found = this.products.find(el =>
el.productName.toLowerCase() == str.toLowerCase())
if (found) {
if (found.amount > 1) {
const foundIndex = this.products.findIndex(x => x.productName.toLowerCase() === str.toLowerCase());
this.products[foundIndex].amount = found.amount - 1;
} else {
this.products.splice(this.products.findIndex(
item => item.productName.toLowerCase() === str.toLowerCase()), 1)
}
}
return this;
}
sumPrice(str, num) {
const foundIndex = this.products.findIndex(x => (x.productName || '').toLowerCase() === str.toLowerCase());
if (foundIndex >= 0) {
this.products[foundIndex].cost = this.products[foundIndex].cost + num;
}
return this;
}
sumTotal() {
this.total = 0;
for (let obj of this.products) {
this.total += obj.amount * obj.cost;
}
return this;
}
write() {
let total = 0;
for (let obj of this.products) {
console.log('Item: ' + obj.productName + ' | Quantity:' + obj.amount + ' | Price:' + obj.cost);
total += obj.amount * obj.cost;
}
console.log('$' + total);
}
}
new ProductsStore()
.buyProduct({ productName: 'jameson', amount: 1, cost: 0 })
.buyProduct({ productName: 'bud light', amount: 3, cost: 0 })
.buyProduct({ productName: 'corona', amount: 4, cost: 0 })
.buyProduct({ productName: 'beer', amount: 1, cost: 0 })
.sumPrice('tequila', 5.99)
.deleteProduct('corona')
.sumPrice('beer', 5.04)
.sumTotal()
.write();
你应该从你的所有方法中返回“this”。
有些方法没有返回“this”,如:
sumPrice():
if(foundIndex>=0)
{
products[foundIndex].cost = products[foundIndex].cost + num;
}
return this;// this should be returned here.
deleteProduct():
应该在函数结束时返回“this”。
总和():
而不是返回总数,你应该返回。
最后,你应该为总数返回一个吸气剂。