这是我的“添加到卡”功能
addToCart(product){
this.storage.get("cart").then((data) =>{
if (data == null || data.length == 0){
data = [];
data.push({
"product": product,
"qty": 1,
"amount": parseFloat(product.price)
});
} else {
let added = 0;
for (let i = 0; i < data.length; i++)
{
if( product.id == data[i].product.id )
{
console.log("Product is already in the cart");
let qty = data[i].qty;
data[i] = qty+1;
data[i].amount = parseFloat(data[i].amount) + parseFloat(data[i].product.price);
added = 1 ;
}
}
if (added == 0 ){
data.push({
"product": product,
"qty": 1,
"amount": parseFloat(product.price)
});
}
}
this.storage.set("cart", data).then( ()=>{
console.log("updated");
console.log(data);
this.toastCtrl.create({
message: "Cart Updated",
duration: 3000
}).present();
})
});
}
当我单击“添加到卡”按钮时,该产品已成功添加。但是,当我再次单击它时,它向我显示该产品已经添加,但出现错误“无法读取未定义的属性'price'”。 这是图像
答案 0 :(得分:0)
您的问题在这里:
data[i] = qty+1;
可能应该是:
data[i].qty = qty + 1;
const data = [{
qty: 1,
amount: 50,
product: {
price: 20,
},
}];
const i = 0;
let qty = data[i].qty;
console.log('before', data[i]);
console.log('before access', data[i].product.price);
// Problem is here
data[i] = qty + 1;
console.log('after', data[i]);
console.log('after access', data[i].product.price);
data[i].amount = parseFloat(data[i].amount) + parseFloat(data[i].product.price);
答案 1 :(得分:0)
问题是您在此处将数据[i]分配给整数:
data[i] = qty+1;
应为:
data[i].qty = qty+1;