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

JavaScript中如何过滤数组0值并查找剩余元素的最大值

实现方案

你可以直接通过数组的filter方法过滤0值,再配合Math.max获取最大值,具体代码如下:

const originalArr = [
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  4116.38,
  4120.87,
  0,
  0,
  0,
];

// 方式1:分步骤写,可读性更强
const nonZeroArr = originalArr.filter(item => item !== 0)
const maxValue = Math.max(...nonZeroArr)
console.log(maxValue) // 输出结果:4120.87

// 方式2:链式调用,写法更简洁
const maxValueShort = Math.max(...originalArr.filter(item => item !== 0))

边界情况处理

如果原数组全是0,过滤后得到的是空数组,直接调用Math.max(...[])会返回-Infinity,你可以根据需要加判断处理:

const nonZeroArr = originalArr.filter(item => item !== 0)
const maxValue = nonZeroArr.length ? Math.max(...nonZeroArr) : 0 // 空数组时可自定义返回默认值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:54:04