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

JavaScript如何优雅查找前缀和达到指定阈值时对应的数组索引

首先你的现有实现其实已经是性能最优的方案:遍历过程中命中条件直接返回,不会做多余的遍历,时间复杂度O(n)、空间复杂度O(1),符合JS的编码习惯。

如果想要更简洁、语义更贴合的写法,可以用Array.prototype.findIndex实现,代码如下:

function findIndex(nums, limit) {
  let sum = 0
  const targetIndex = nums.findIndex(num => (sum += num) >= limit)
  // 处理所有前缀和都小于阈值的边界,和你原有逻辑保持一致返回数组长度
  return targetIndex === -1 ? nums.length : targetIndex
}

这个写法和你的原有逻辑完全等价,而且findIndex本身就是用来查找第一个符合条件的元素索引的原生方法,语义更清晰。

如果你确实想用reduce实现也可以,但不推荐:因为reduce会强制遍历完整个数组,无法在命中条件时提前终止,性能比前两种方案差,代码也更啰嗦,仅做参考:

function findIndex(nums, limit) {
  return nums.reduce((acc, cur, index) => {
    if (acc.matched) return acc
    acc.sum += cur
    if (acc.sum >= limit) {
      acc.result = index
      acc.matched = true
    }
    return acc
  }, { sum: 0, result: nums.length, matched: false }).result
}

日常开发优先选择findIndex的实现方案即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:54:07