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

twoSum算法疑问:调用函数返回undefined,内部可访问结果外部不行

为什么twoSum函数调用后返回undefined?

你的twoSum函数在外部调用时返回undefined,核心原因是函数没有显式返回计算结果。在JavaScript中,任何函数如果没有使用return语句指定返回值,默认都会返回undefined——这就是你用console.log(twoSum(...))输出undefined的原因。

你在函数内部已经正确计算出了符合条件的索引数组arrayOfIndices,甚至赋值给了result,但只是在函数内部用console.log打印了结果,并没有把这个值传递到函数外部。

修改方案

只需在函数末尾添加return语句,把计算结果返回即可:

function twoSum(nums, target) {
    console.log(nums); // keep track of user input.
    console.log(target); // keep track of target.

    let arrayOfIndices = [];

    // loop through array and perform addition operation
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                arrayOfIndices.push([i, j]);
            }
        }
    }

    if (arrayOfIndices.length === 0) {
        console.log("No two sum exists");
    } else {
        console.log(arrayOfIndices);
    }
    let result = arrayOfIndices;
    console.log(result);
    // 添加return语句返回结果到外部
    return result;
}

// Test case
console.log(twoSum([3, 4, 5], 7)); // 现在会输出 [[0,1]]

可选优化

你也可以把结果判断和返回逻辑结合,让代码更简洁,比如没找到符合条件的组合时返回空数组(可根据需求调整返回值):

function twoSum(nums, target) {
    let arrayOfIndices = [];

    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                arrayOfIndices.push([i, j]);
            }
        }
    }

    if (arrayOfIndices.length === 0) {
        console.log("No two sum exists");
        return [];
    }
    console.log(arrayOfIndices);
    return arrayOfIndices;
}

添加return语句后,函数调用时就会把计算得到的结果传递到外部,外部的console.log就能正确输出你需要的索引数组,而不是undefined了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:15:30