Javascript 每次添加产品时增加totalAmount
我有一个问题,当我添加一个产品的总量显示我20我不知道为什么?如果我增加总量,但总量不移动,我怎么做呢 谢谢 ts.fileJavascript 每次添加产品时增加totalAmount,javascript,angular,typescript,cart,Javascript,Angular,Typescript,Cart,我有一个问题,当我添加一个产品的总量显示我20我不知道为什么?如果我增加总量,但总量不移动,我怎么做呢 谢谢 ts.file productList = [ { id: 1, name: 'Louis Vuis', price: 10, qtn: 1 }, { id: 2, name: 'shubert helmet', price: 20, qtn: 1 }, ]; productArray: any = []; totalAmount: number
productList = [
{ id: 1, name: 'Louis Vuis', price: 10, qtn: 1 },
{ id: 2, name: 'shubert helmet', price: 20, qtn: 1 },
];
productArray: any = [];
totalAmount: number;
ngOnInit() {
this.totalPrice();
}
add(product, idx) {
const found = this.productArray.find(
item => JSON.stringify(item) === JSON.stringify(product)
);
if (found) {
this.productArray[idx].qtn++;
} else {
this.productArray.push(product);
}
}
totalPrice() {
this.productList.forEach(item => {
this.totalAmount = (item.qtn * item.price)
console.log(this.totalAmount);
});
}
我觉得问题出在别的地方。你所做的是对的
totalPrice() {
this.productList.forEach(item => {
this.totalAmount = (item.qtn * item.price)
console.log(this.totalAmount);
});
}
但您正在迭代javascript对象并将该值分配给total amount
因此,在迭代过程中,如果您希望根据数量显示每个项目的价格,则需要在产品的新键中指定值
类似于item.total=(item.qtn*item.price)代码>
如果您想在totalAmount中显示所有值的总和,则需要执行this.totalAmount+=(item.qtn*item.price)
当您添加数量时,将您正在执行的数量增加1,更新状态并调用this.totalPrice()
有多个问题
添加产品时,您将其添加到productArray
中,但在计算总量时,您将从productList
中计算。无论您在productArray中添加了多少产品,这都将为您提供恒定的totalAmount
this.totalAmount=(item.qtn*item.price)
将更新后的值重新分配到totalAmount中,而不是添加到以前的值中。您需要编写,this.totalAmount+=(item.qtn*item.price)
据我所知,我正在更新totalPrice方法。不确定这是否有帮助
totalPrice() {
this.productList.forEach(item => {
let productIndexInProductArray = productArray.findIndex(p => p.id === item.id);
if(productIndexInProductArray > -1) {
this.totalAmount += (productArray[productIndexInProductArray].qtn * item.price)
console.log(this.totalAmount);
}
});
}
问题是totalAmount
id定义但未初始化
因此,第一个更改是需要初始化totalAmount
totalAmount: number = 0;
第二个更改需要在totalPrice
函数中执行,因为每次计算金额时,项目金额设置为totalAmount
所以totalAmount
将每个项目重置,这就是为什么您在控制台中获得最后一个项目金额。您需要在totalAmount
中添加项目金额,如下所示
totalPrice() {
this.productList.forEach(item => {
this.totalAmount += (item.qtn * item.price)
console.log(this.totalAmount);
});
}
this.totalAmount+=(item.qtn*item.price)Mohammed,您应该解释答案,而不仅仅是发布代码。1.您需要初始化totalAmount=0。您在代码中遗漏了这一点。然后第二行this.totalAmount+=(item.qtn*item.price)这实际上意味着this.totalAmount=this.totalAmount+(item.qtn*item.price)。在forloop中,您正在迭代循环并将值存储在这个.totalAmount中。在第一个循环中,您将得到10,在第二个循环中得到20。因此,totalAmount是10+20=30不,我告诉过您在输入代码后解释您的答案,而不是在注释中,这不是给我的,而是给看到您答案的用户的解释,我从stackoverflow那里得到了改进你答案的建议,所以我给了你一个建议,所以没有必要在评论中解释,而是在答案中解释,谢谢。
totalPrice() {
this.productList.forEach(item => {
this.totalAmount += (item.qtn * item.price)
console.log(this.totalAmount);
});
}