【问题标题】:How to return summed array from computed using reduce function. Vuejs如何使用 reduce 函数从计算中返回求和数组。 Vuejs
【发布时间】:2019-06-13 01:55:28
【问题描述】:

我是 js 新手,很抱歉,如果我描述得不够好,无法理解我在哪里挣扎,要解释我需要什么真的不容易。

我有一个计算函数,使用 reduce 方法循环我的对象,在循环内进行一些计算以查找新变量并返回带有求和值的数组。

我知道如何在循环内返回值的总和,但只有一个变量,我不知道如何从计算中返回 2 个变量,这就是为什么我认为将这 2 个值转换为数组并以某种方式返回总和,在未来的计算中使用这 2 个值。请提示我,在哪里挖。 我的代码更好地解释了这个问题:

 new Vue({
        el: "#demo",
        data() {
            return {
            objects: {
                price: 0,
                amount: 0,
                percent: 0,
                fee: 0,
                solution_cost: {dry:0, wet: 0}
            },
        },
        computed: {
            solutionCost() {
                //Looping thru my objects
                const total = this.objects.reduce((sum, object) => {

                    solution_cost_dry = object.amount / object.price;
                    solution_cost_wet = object.solution_cost[dry] * object.percent;

                    // Don't undestand how to get sum vor "dry" and "wet" and put it summed into array
                    return object.solution_cost: sum + {dry:solution_cost_dry, wet:solution_cost_wet  }

                }, 0)

                //return array with summed values {dry:solution_cost_dry, wet:solution_cost_wet  }
                return total[];
            },
        }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

【问题讨论】:

  • 您不是在尝试返回一个数组,而是在尝试返回一个带有两个键的对象
  • 试试return sum + solution_cost_dry + solution_cost_wet

标签: javascript vue.js


【解决方案1】:

我已将 //CHANGE cmets 添加到我更改逻辑的代码中。您需要传入要返回的初始对象,并更新总计的嵌套键。

computed: {
    solutionCost() {
        //Looping thru my objects
        const total = this.objects.reduce((sum, object) => {
            solution_cost_dry = object.amount / object.price;
            solution_cost_wet = object.solution_cost[dry] * object.percent;

            //CHANGE: add the values to the totals
            sum.dry += solution_cost_dry;
            sum.wet += solution_cost_wet;
            
            return sum;
        }, {dry:0, wet:0}) //CHANGE: Make the initial "sum" be the object with each key with a zero value

        //return array with summed values {dry:solution_cost_dry, wet:solution_cost_wet  }
        return total;
    },
}

【讨论】:

  • return total[]; 应该是return total;
猜你喜欢
  • 2016-05-27
  • 2018-05-01
  • 2020-07-31
  • 2018-05-11
  • 1970-01-01
  • 2019-01-16
  • 2016-10-04
  • 1970-01-01
  • 2019-10-28
相关资源
最近更新 更多