You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript计算不区分大小写的ROMAN类图书的平均价格

实现思路

你之前单独提取所有type转小写的操作没有和对应图书的price字段关联,无法直接用来计算价格,我们可以按以下步骤实现:

  1. 遍历图书列表时直接判断每条数据的type(转小写后是否等于roman)
  2. 筛选出所有符合条件的图书
  3. 累加符合条件图书的价格,除以符合条件的图书数量得到平均值,注意处理无符合条件数据的场景避免除以0报错

代码实现

分步写法(可读性更高)

// 筛选所有类型为roman的图书(不区分大小写)
const romanBooks = books.filter(book => book.type.toLowerCase() === 'roman')
// 计算符合条件的图书总价
const totalPrice = romanBooks.reduce((sum, cur) => sum + cur.price, 0)
// 计算平均值,无符合条件数据时返回0避免NaN
const averagePrice = romanBooks.length ? totalPrice / romanBooks.length : 0

单遍历写法(性能更好,适合大数据量场景)

只需要遍历一次数组就能完成统计:

const { total, count } = books.reduce((acc, cur) => {
  if (cur.type.toLowerCase() === 'roman') {
    acc.total += cur.price
    acc.count += 1
  }
  return acc
}, { total: 0, count: 0 })
const averagePrice = count ? total / count : 0

用你给出的测试数据计算,最终得到的平均价格是(204.5 + 321 + 204.5 + 245.5) / 4 = 243.875。

内容的提问来源于stack exchange,提问作者Marta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:27:03