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

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

添加二維對象的值 - forEach?

添加二維對象的值 - forEach?

絕地無雙 2022-08-27 10:55:06
如何迭代并獲取子對象內所有值的總和?在下面的示例中,我想添加所有.windowslet house = {  livingroom: { windows: 6, doors: 4 },  bedroom: { windows: 4, doors: 2 },  bathroom: { windows: 2, doors: 1 },  garden: { windows: 0, doors: 2 }}我也試過:Object.values(house).reduce(sum, curr => sum + curr));&let x += Object.values(house).forEach(sum => sum);
查看完整描述

2 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

你可以試試這個

Object.values(house).map(item => item.windows).reduce((accumulator, currentValue) => accumulator + currentValue)



查看完整回答
反對 回復 2022-08-27
?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

如果理解正確,則需要循環訪問這些值,可以使用:Object.values


let house = {

  livingroom: { windows: 6, doors: 4 },

  bedroom: { windows: 4, doors: 2 },

  bathroom: { windows: 2, doors: 1 },

  garden: { windows: 0, doors: 2 }

}


let count = { windows: 0, doors: 0 }


for (const room of Object.values(house)) {

  count.windows += room.windows

  count.doors += room.doors

}


console.log(count)


查看完整回答
反對 回復 2022-08-27
  • 2 回答
  • 0 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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