【问题标题】:How to perform calculation in object array using javascript如何使用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 感谢您的回复,对不起,它的对象数组。更新代码

标签: javascript jquery arrays object


【解决方案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。
    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多