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

JavaScript中用forEach替换for循环实现两数之和为何返回undefined?

问题原因

你遇到的差异完全是forEach的语法设计导致的,核心有两点:

  1. Array.prototype.forEach 固定返回undefined
    这是ECMAScript规范明确定义的,无论传入的回调函数内部返回什么内容,都不会改变forEach自身的返回值。而普通for循环没有返回值限制,循环内的return是直接作用于循环所在的外层函数,会把值直接返回给调用方。
  2. forEach 回调内的return无法透传、也不能终止遍历
    你在forEach回调中写的return [index,index+1],仅会终止当前这一轮回调的执行,不会中断整个数组的遍历,同时这个返回值会被forEach内部直接丢弃,无法传递到外层作用域。

你测试时两边console.log都能正常输出[0,1],是因为条件匹配时回调确实执行到了打印逻辑,但回调的返回值被吞掉了,所以最终拿到的forEach调用结果就是undefined。

替代方案

如果不想用普通for循环,可以用for...of或者数组查找方法实现相同效果,比如:

// 用for...of实现,支持直接return
for (const [index, item] of nums.entries()) {
  const targetNum = target - item
  const targetIndex = nums.indexOf(targetNum, index + 1)
  if (targetIndex > -1) {
    console.log([index, targetIndex])
    return [index, targetIndex]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:27:04