簡體   English   中英

如何從使用reduce函數計算得出的數組中返回求和數組。 Vuejs

[英]How to return summed array from computed using reduce function. Vuejs

我是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> 

我在更改邏輯的代碼中添加了// CHANGE注釋。 您需要傳遞要返回的初始對象,然后更新總計的嵌套鍵。

 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; }, } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM