第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

從遞歸中得到總數(shù)

從遞歸中得到總數(shù)

慕工程0101907 2023-05-11 15:57:46
我有一個(gè)對(duì)象數(shù)組,它引用了它的集合const data = [{    id: 1,    name: 'A',    referer_id: null,    point: 4  },  {    id: 2,    name: 'B',    referer_id: 1,    point: 100  },  {    id: 3,    name: 'C',    referer_id: null,    point: 4  },  {    id: 4,    name: 'D',    referer_id: 1,    point: 2  },  {    id: 5,    name: 'E',    referer_id: null,    point: 4  },  {    id: 6,    name: 'F',    referer_id: null,    point: 4  },  {    id: 7,    name: 'G',    referer_id: 2,    point: 4  },];referer id 將引用該 id。我還有另一個(gè)數(shù)字?jǐn)?shù)組用于計(jì)算點(diǎn)const pointsByLevel = [0.5, 0.3, 0.2]; // this would be dynamic from database截至目前,我可以像這樣得到所有總數(shù)的總和function getPoint(user_id) {  const mainUserPoint = data.find((u) => u.id === user_id).point;  let sum = 0;    for (let subdep of data.filter((d) => d.referer_id === user_id)) {    sum += getPoint(subdep.id);  }  return mainUserPoint + sum;}但真正的挑戰(zhàn)是第一級(jí)應(yīng)該只返回點(diǎn)數(shù),但之后點(diǎn)數(shù)將根據(jù)pointsByLevel索引乘以所以輸出會(huì)是這樣的console.log(getPoint(1));/**A - 4B D - [100 * 0.5], [2 * 0.5]G - [4 * 0.3]**/// 4 + 50 + 1 + 1.2 = 56.2所以最終結(jié)果我會(huì)得到 56.2最有效的方法是什么
查看完整描述

1 回答

?
皈依舞

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊

作為 的附加參數(shù),您必須跟蹤您的深度級(jí)別getPoint。將默認(rèn)值設(shè)置為 0,并在每次遞歸時(shí)遞增它。然后你可以為它逐級(jí)找到對(duì)應(yīng)的點(diǎn)。(我為 0 級(jí)插入了 1.0 系數(shù))。我還添加了評(píng)論以顯示每個(gè)級(jí)別的部分結(jié)果。


const data = [

  { id: 1, name: 'A', referer_id: null, point: 4 },

  { id: 2, name: 'B', referer_id: 1, point: 100 },

  { id: 3, name: 'C', referer_id: null, point: 4 },

  { id: 4, name: 'D', referer_id: 1, point: 2 },

  { id: 5, name: 'E', referer_id: null, point: 4 },

  { id: 6, name: 'F', referer_id: null, point: 4 },

  { id: 7, name: 'G', referer_id: 2, point: 4 }

];


const pointsByLevel = [1, 0.5, 0.3, 0.2]; //  NOTE: I added a 1.0 for level 0


function getPoint(user_id, level = 0) {

  const user = data.find((u) => u.id === user_id);

  const mainUserPoint = user.point;

  let sum = 0;


  for (let subdep of data.filter((d) => d.referer_id === user_id)) {

    let val = getPoint(subdep.id, level + 1);

    sum += val;

  }

  let result = (mainUserPoint * pointsByLevel[level]) + sum;

  console.log(`getPoint for ${user_id} "${user.name}" is ${level} levels deep and has the value ${result}`)

  return result;

}


console.log(getPoint(1));


查看完整回答
反對(duì) 回復(fù) 2023-05-11
  • 1 回答
  • 0 關(guān)注
  • 136 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)