如何使用javascript在对象数组中执行计算
Posted
技术标签:
【中文标题】如何使用javascript在对象数组中执行计算【英文标题】:How to perform calculation in object array using javascript 【发布时间】:2019-09-26 20:26:02 【问题描述】:我在 javascript 的嵌套对象数组中执行计算。 如图所示,我有两个输入
对于obj
如果obj.rate > mr
那么
cr = (((obj.amount * obj.rate) - (obj.amount * mr))/(obj.amount * obj.rate))*100 + "%",
totalcost = (obj.netfee-(cr*amountwithfee)
如果obj.rate < mr
那么
cr = (((obj.amount * mr) - (obj.amount * obj.rate))/(obj.amount * mr))*100 + "%",
totalcost = (obj.netfee+(cr*amountwithfee)
如何在下面的函数中精确地进行上述计算
var result = obj.forEach(e=>
..obj,
netfee: obj.fee + obj.payfee,
amountwithfee: obj.amount-obj.netfee,
cr: (((obj.amount * mr) - (obj.amount * obj.rate))/(obj.amount * mr))*100 + "%",
totalcost: (obj.netfee+(cr*amountwithfee);
)
console.log(result);
输入
var mr = 0.5;
var obj =[
amount: 1000,
fee: 5,
payfee:2,
rate:0.49
]
预期输出:
result = [
amount: 1000,
fee: 5,
payfee: 2,
netfee: 7,
amountwithfee: 993,
rate: 0.49,
cr : -2%,
totalcost: 26.86
]
【问题讨论】:
这很令人困惑,因为您正在调用obj.forEach
但 obj
不是数组。 forEach()
也不返回任何东西。你是从一个对象还是对象数组开始?
@MarkMeyer 感谢您的回复,对不起,它的对象数组。更新代码
【参考方案1】:
//initiallizing
var mr = 0.5;
var obj =[
amount: 1000,
fee: 5,
payfee:2,
rate:0.49
,
amount: 1000,
fee: 5,
payfee:2,
rate:0.5
];
var result = [];
//start calculation
obj.forEach(x =>
let netfee = 0;
let amountwithfee = 0;
let cr = 0;
let totalcost = 0;
netfee = x.fee + x.payfee;
amountwithfee = x.amount- netfee;
//write your login
if (x.rate < mr)
cr = (((x.amount * mr) - (x.amount * x.rate))/(x.amount * mr))*100;
totalcost = (netfee + (cr * amountwithfee));
else
cr = (((x.amount * x.rate) - (x.amount * mr))/(x.amount * x.rate))*100;
totalcost = (netfee - (cr * amountwithfee));
//generate output
result.push(
'amount': x.amount,
'fee': x.fee,
'payfee': x.payfee,
'netfee': netfee,
'amountwithfee': amountwithfee,
'rate': x.rate,
'cr': cr + "%",
'totalcost': totalcost
);
);
console.log(result);
【讨论】:
【参考方案2】:在进行数学计算时,在需要时使用parseInt()
和parseFloat()
,或使用eval()
进行运算。
【讨论】:
我永远不会推荐使用eval()
。我将能够执行任何我想执行的js。以上是关于如何使用javascript在对象数组中执行计算的主要内容,如果未能解决你的问题,请参考以下文章