javascript - 有没有办法专门使用多维数组中的第二个值来进行计算
问题描述
例如,如果我只想从数组中选择数值并计算小费金额并计算账单的总和。
let bill = [["Fish", 23], ["Steak", 10],["Avocado Toast", 15]];
bill.forEach((dish) => {
dish.forEach((dishAmount)=> {
console.log(dishAmount);
})
})
解决方案
使用对象解构访问第二个元素(在索引 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)
推荐阅读
- php - 自定义中间件 Laravel 不适用于 api 路由
- python - 如何创建字典映射到一组值以避免字典中的相同键
- reactjs - 如何在 react-redux 中重用动作创建者?
- python - 动态分组条形图
- python - Python迭代列表日期时间值
- python-3.x - 在python中解析日期时间
- service-worker - 如果多个用户使用同一个设备怎么办?
- c - 带有 SIG_BLOCK 的 sigprocmask 不会阻止 SIGALRM
- javascript - 使用 Google Apps 脚本和 Google 课堂创建学生
- asp.net-core - Razor 页面中的路由数据