繁体   English   中英

如何返回删除美元符号的平均客户余额?

[英]How can I return the average customer balance with the dollar sign removed?

我正在尝试使用此代码返回不带美元符号或逗号的平均客户余额。 我正在使用.reduce,因为我觉得这是最好的选择。 此外,我是第一次尝试 parseFloat,所以我不确定我是否正确使用它。 这里的目标是

  1. 将字符串转换为数字并将美元符号和逗号替换为空
  2. 总结所有余额
  3. 返回平均余额
  4. 使用.reduce
var people = [
  {
    name: "Courtney",
    age: 43, 
    balance: "$3,400"
  },
  {
    name: "Regina",
    age: 53,
    balance: "$4,000"
  },
  {
    name: "Jay",
    age: 28,
    balance: "$3,000"
  },
]

var averageBalance = function(array){
   var average = people.reduce(function(acc, current, index, array){
     if(index === array.length - 1){
       return acc / array.length; 
     }
     return acc += parseFloat(current.balance.replace(/\$|,/g, ""));
   }, 0); 
 return average;
}

你试图在你的.reduce体内做太多事情。 .reduce让你可以对数组的每个元素做一些事情——比如把它们全部加起来。 如果您想单独做一件事(例如除以数组的长度以获得平均值),则应将其放在.reduce回调之外。

 var people = [{ name: "Courtney", age: 43, balance: "$3,400" }, { name: "Regina", age: 53, balance: "$4,000" }, { name: "Jay", age: 28, balance: "$3,000" }, ] var averageBalance = function(array) { const sum = people.reduce(function(acc, current) { return acc + Number(current.balance.replace(/\$|,/g, "")); }, 0); return sum / people.length; } console.log(averageBalance(people));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM