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

如何使用reduce方法获取满足求和条件的相邻JavaScript数组元素索引?

使用reduce方法查找相邻元素求和匹配的索引

当然可以用reduce实现这个需求,不过reduce本身是为累加场景设计的,我们可以借助它遍历数组的特性来完成检查:

function indexes(sum, data) {
  const match = data.reduce((found, current, idx) => {
    // 已找到匹配项就直接返回,终止后续遍历
    if (found) return found;
    // 跳过最后一个元素(无相邻下一个元素)
    if (idx === data.length - 1) return found;
    // 检查当前元素与下一个元素的和是否符合条件
    if (current + data[idx + 1] === sum) {
      return [idx, idx + 1];
    }
    return found;
  }, null);

  return match || 'no match';
}

不过要说明的是,你原本的for循环写法已经足够简洁高效——时间复杂度O(n),找到匹配项就立即返回,不需要遍历整个数组。如果追求更优雅的写法,用findIndex会更直观:

function indexes(sum, data) {
  const targetIdx = data.findIndex((num, idx) => idx < data.length - 1 && num + data[idx + 1] === sum);
  return targetIdx !== -1 ? [targetIdx, targetIdx + 1] : 'no match';
}

findIndex会直接返回第一个满足条件的元素索引,逻辑清晰,代码量也更少,和你的原实现性能一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:26:16