【问题标题】:how to get sum of array in vue js using computed?如何使用计算获得vue js中的数组总和?
【发布时间】:2020-10-05 07:55:38
【问题描述】:

这是我的查询结果

{1: {deduction: 625}, 2: {deduction: 500}, 3: {deduction: 2500}, grandTotal: 8460, otTotal: 50,…}
1: {deduction: 625}
2: {deduction: 500}
3: {deduction: 2500}
allowance: 0
grandTotal: 8460
otTotal: 50

我在 vue 中计算得到一个错误"TypeError: this.grand.reduce is not a function"

totaldeduct(){
return this.grand.reduce((acc, item)=>{
return acc+ Number(item.deduction)
},0)
}

【问题讨论】:

    标签: javascript arrays vue.js


    【解决方案1】:

    Reduce() 是 javascript 中的数组函数。您要么想为您的对象使用 forEach,要么将其重写为数组。

    const data = [
          { deduction: 625 },
          { deduction: 500 },
          { deduction: 2500 },
          { grandTotal: 8460 },
          { otTotal: 50 },
        ];
    
        function totaldeduct(data) {
          return data.reduce((acc, item) => {
            if(item.deduction)
              return acc + item.deduction;
            else return acc
          }, 0);
        }
    
        let reduced = totaldeduct(data);
    
        console.log(reduced);

    【讨论】:

    • 我只想得到deduction的总数?
    • 我已经给你答案了,作为 JS 开发者,重写它应该不难。 if(item.deduction) return acc + item.deduction; else return acc
    • 对不起,我是初学者
    • 不工作,兄弟。我认为因为它是一个对象,我怎样才能将它转换成数组?
    • 我明白了兄弟..!
    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 2017-01-03
    • 2019-09-23
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多