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

JavaScript实现Two Sum返回undefined问题排查求助

解决Two Sum函数返回undefined的问题

问题根源

  • forEach回调的return无法传递到外层函数:你在forEach的回调函数里return res,但forEach方法不会处理回调的返回值,外层的numbers函数没有任何顶层的return语句,所以调用后默认返回undefined。
  • 索引0被误判为假值:当计算得到补数对应的索引是0时,if(j)会把0当成假值跳过(JS里0、''、null、undefined都是假值),导致错过正确的匹配逻辑,循环会执行完所有元素。
  • 字符串模板语法错误:单引号包裹的[ ${j} ${i} ]不会解析变量,必须用反引号`才能生效,这会导致就算返回结果,内容也不是预期的插值字符串。

修正后的代码(推荐用for循环,效率更高)

var num = [2, 7, 11, 15]

function numbers(target) {
  var idx = {}
  for (var i = 0; i < num.length; i++) {
    var n = num[i]
    var complement = target - n
    // 明确判断补数对应的索引是否存在,避免0被误判
    if (idx[complement] !== undefined) {
      return `[ ${idx[complement]} ${i} ]`
    }
    idx[n] = i
  }
  // 没有找到符合条件的数对时返回null,可根据需求调整
  return null
}

console.log(numbers(9)) // 输出: [ 0 1 ]

另一种写法(用forEach)

如果坚持用forEach,需要在外层定义变量存储结果,最后统一返回:

var num = [2, 7, 11, 15]

function numbers(target) {
  var idx = {}
  var result
  num.forEach(function(n, i) {
    var complement = target - n
    if (idx[complement] !== undefined) {
      result = `[ ${idx[complement]} ${i} ]`
    }
    idx[n] = i
  })
  return result
}

console.log(numbers(9)) // 输出: [ 0 1 ]

注意:forEach无法中途终止循环,就算找到结果也会遍历完所有元素,所以for循环的效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:51:37