首页 > 解决方案 > 有没有办法专门使用多维数组中的第二个值来进行计算

问题描述

例如,如果我只想从数组中选择数值并计算小费金额并计算账单的总和。

let bill = [["Fish", 23], ["Steak", 10],["Avocado Toast", 15]];

bill.forEach((dish) => {
  dish.forEach((dishAmount)=> {
    console.log(dishAmount);
  })
})

标签: javascriptarraysmultidimensional-array

解决方案


使用对象解构访问第二个元素(在索引 1 处)

let bill = [["Fish", 23], ["Steak", 10],["Avocado Toast", 15]];

let total = 0;
bill.forEach(({1: dishAmount}) => {
  console.log(dishAmount);
  total += dishAmount;
})

console.log('total', total)

// Alternatively
const total2 = bill.reduce((acc, {1: dishAmount}) => acc + dishAmount, 0)

console.log('total 2', total2)


推荐阅读