TypeError:在使用getter js时不能读取undefined的属性



我构建了两个类,一个是包含名称和价格的产品,一个是包含产品数组的购物车;对于ShoppingCart get totPrice方法,我在构造函数的数组购物车上使用reduce()函数,但我总是得到上面的错误,我不明白为什么。

class Product {
constructor(name,price) {
this.name = name;
this.price = price;
}
toString() {
console.log(this.name + ' - ' + this.price);
}
}
class ShoppingCart {
constructor(cart) {
this.cart = cart;
}
get totPrice() {
return this.cart.reduce((el1,el2) => {el1.price + el2.price});
}
addProd = function(prod) {
this.cart.push(prod);
this.cart.totPrice += prod.price;
if(this.cart.length >= 5){
this.totPrice = this.totPrice * 0.9;
}
if(this.cart.filter(tmp => tmp.name === prod.name).length % 4 === 0){
this.totPrice -= prod.price;
}
}
removeProd = function(prod) {
let i = this.cart.findIndex(el => {prod.name === el.name});
this.cart.splice(i,1);
console.log(`The product ${prod.name} has been removed from your shopping cart`);
}
} 
let prod1 = new Product('Apple',15);
let prod2 = new Product('Banana',20);
let prod3 = new Product('Melon',25);
let shopCart = new ShoppingCart([prod1,prod2,prod3]);
console.log(shopCart.totPrice);

这里已经解释了这个问题的答案。

在第一次迭代后,你返回一个数字,然后试图获得属性sum。将其添加到下一个未定义的对象中。您还需要一个求和的初始值。

get totPrice() {
return this.cart.reduce((acc,el) => acc + el.price,0);
}

最新更新