亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在js ES6中的破壞結構中傳遞多個參數

如何在js ES6中的破壞結構中傳遞多個參數

夢里花落0921 2022-07-21 11:03:16
我有一個元素數組,我試圖做幾列。我已經閱讀了有關從中解構元素的 reduce 方法。但問題是我無法在其中傳遞多個參數。另外,它不識別其中傳遞的元素。這是我的代碼:const prob = h.lead_plans.reduce((currentTotal, currentDau) => {                                            console.log(currentDau.probability);                                            return  ({'probability'} = {probability: ((currentTotal || 0) + currentDau.probability)})                                        }, {probability: 0});預期代碼:const prob = h.lead_plans.reduce((currentTotal, currentDau) => {                                            return  ({probability,plan2} = {                                                probability: ((currentTotal || 0) + currentDau.probability),                                                plan2: ((currentTotal || 0) + currentDau.plan2),                                            })                                        }, {probability: 0, plan2: 0});作為最終結果,我將獲得基于解構結構的內部列的總和。
查看完整描述

1 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

以下是代碼的工作方式。currentTotal第一次運行的值是 reduce 函數的第二個參數,而Array#reduce(function,initialValue)不是{probability: 0, plan2: 0}一個數字。


所以,你不需要做任何對象解構,你只需要使用累加器對你想要的對象的各個鍵求和,然后返回這些新值。然后您的最終結果將與您用于初始值的類型相同。


這會將概率和 plan2 值轉換為數字,以便能夠正確地求和。


const h = {

  lead_plans: [{

    probability: '2.2',

    plan2: '5.2'

  }, {

    probability: '7.8',

    plan2: '3.1'

  }, {

    probability: '1.8',

    plan2: '2.3'

  }]

}

const result = h.lead_plans.reduce(

  (accumulator, currentDau) => {

    return {

      probability: accumulator.probability + parseFloat((currentDau.probability || 0)),

      plan2: accumulator.plan2 + parseFloat((currentDau.plan2 || 0)),

    };

  }, {

    probability: 0,

    plan2: 0

  }

);

console.log(result);

下面是一個示例,說明如何制作一個更可重用的 reducer 來匯總對象中的所有條目:


請注意,這是將所有鍵轉換為數字,因此如果存在不是數字的值,它們將是 NaN。


const h = {

  lead_plans: [{

    probability: '2.5',

    plan2: 5

  }, {

    probability: 7,

    plan2: 3

  }, {

    probability: 1,

    plan2: 2

  }]

}

const reducerSumAll = (accumulator, object) => {

  // Ensure there are no accidental mutations

  const current = { ...accumulator };

  for (const key of Object.keys(object)) {

    // Make sure we are only accumulating the number types.

    current[key] = parseFloat(current[key]||0) + parseFloat(object[key]||0);

  }

  return current;

};

const result = h.lead_plans.reduce(reducerSumAll)

console.log(result)


查看完整回答
反對 回復 2022-07-21
  • 1 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號