实现说明
顶层就这几处状态:orders、euTotal、allPrices。
使用要点
- 演示输出是带标签的(
eu total:、prices:、has na order:),每个操作都会留下自己的一行标注。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件用顶层绑定保存自己的状态:orders、euTotal、allPrices。
核心语句
.reduce((sum, o) => sum + o.items.reduce((s, i) => s + i.price, 0), 0);
const allPrices = orders.flatMap((o) => o.items.map((i) => i.price));
代码示例
const orders = [
{ id: 1, region: 'eu', items: [{ price: 10 }, { price: 20 }] },
{ id: 2, region: 'na', items: [{ price: 5 }] },
{ id: 3, region: 'eu', items: [{ price: 30 }] },
];
// filter → map → reduce:日常列表处理三板斧
const euTotal = orders
.filter((o) => o.region === 'eu')
.reduce((sum, o) => sum + o.items.reduce((s, i) => s + i.price, 0), 0);
console.log('eu total:', euTotal);
// flatMap:一层展开(拍平子列表)
const allPrices = orders.flatMap((o) => o.items.map((i) => i.price));
console.log('prices:', allPrices);
// 查找与判断
console.log('has na order:', orders.some((o) => o.region === 'na'));
console.log('first big order:', orders.find((o) => o.items.length > 1)?.id);