javascript - 将对象值减去数组不正确
问题描述
我正在尝试对数组对象的总价格求和,然后在该数组之外添加总价格。
例子 :
[
{
"addons": [
{
"title": "خبز بعجين",
"price": 0.1,
"selected": true
},
{
"title": "لحم بعجين ",
"price": 2,
"selected": true
},
{
"title": "ببسي بارد",
"price": 55,
"selected": true
},
{
"title": "كولا ",
"price": 4,
"selected": true
}
],
"Totaladdons": 61.1, // < total price of array above .
"price" : 300 // < sum Totaladdons with this object price .
}
]
sum(data) {
let totalPrice = 0;
let currency: any
currency = this.items_local[data.index].addons.map(curr => parseFloat(curr.price)).reduce((a, b) => a + b, 0)
console.log(currency);
this.items_local[data.index].Totaladdons = Number(currency);
if (this.items_local[data.index].Totaladdons) {
totalPrice = Number(this.items_local[data.index].Totaladdons) + Number(this.items_local[data.index].price)
this.items_local[data.index].price = totalPrice.toFixed(2)
}
}
删除元素数组对象然后恢复总价的减法
minus(data) {
if (this.items_local[data.index].addons.length > 0) {
for (var i = this.items_local[data.index].addons.length - 1; i >= 0; i--) {
if (this.items_local[data.index].addons[i].title === data.addon.title) {
this.items_local[data.index].addons.splice([i], 1);
// here l am try to resuming the price of array object
currency = this.items_local[data.index].addons.map(curr => parseFloat(curr.price)).reduce((a, b,) => a - b, 0);
console.log(currency);
if (this.items_local[data.index].Totaladdons) {
this.items_local[data.index].Totaladdons = Number(currency);
totalPrice = Number(this.items_local[data.index].price) - Number(this.items_local[data.index].Totaladdons)
this.items_local[data.index].price = totalPrice.toFixed(2)
}
}
}
}
}
问题是当我点击减法时,他没有给我正确的总数。
解决方案
推荐阅读
- javascript - 是否可以在不实际使用“null”的情况下创建“null”值?
- timer - 每个控制器在 JMeter 中的思考时间
- compiler-errors - 如何在 vhdl 中使用“+”操作?
- javascript - 如何在 HTML 画布上拖放文本或图像?
- autohotkey - AHK 初学者:当我尝试随机睡眠时间时,它总是睡最大时间
- java - 如何在一个列表中获取所有复选框值类型可验证
- c# - 在 IIS 上发布后 POST 响应不起作用
- node.js - 有没有办法在nodejs unix环境中使用“js-yaml”将一个YAML文件添加到另一个YAML文件
- sql - Replace 00 with varbinary type
- gtk - GtkApplicationWindow 子类“销毁”两次