js中的两个for循环。不能在嵌套的 for 循环上工作

two for loops in js. cannot work on nested for loop

我正在处理下面的问题,但不确定为什么我的第二个 for 循环执行 console.log 任何操作。我目前得到一个结果,[],当我处理循环时,我有时会感到困惑,因为输出 returns 为空结果。那么为什么我的第二个 for 循环没有执行,为什么我不能将结果推送到结果数组?

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order.

Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].

function a(nums, target) {

let result = [];

for (let i = 0; i < nums.length -1; i++){


    let firstNum = nums[i];

    console.log(i)
    
    for (let j = i + 1; j < nums.length -1; j++){

        console.log(j)
        let secondNum = nums[j];
        
        let sum = firstNum + secondNum;
        
        

        if (sum === target) {
            return result.push(i, j);
            }
        } 
    }
    return result; 
};

a([2,7,11,15], 9)

仅推送return数组的长度,尝试如下,

function a(nums, target) {

    let result = [];

    for (let i = 0; i < nums.length; i++){


        let firstNum = nums[i];

        console.log("i", i)

        for (let j = i + 1; j < nums.length; j++){

            console.log("j", j)
            let secondNum = nums[j];

            let sum = firstNum + secondNum;



            if (sum === target) {
                result.push(i, j);
                return result;
            }
        } 
    }
    return result; 
};

let result = a([2,7,11,15], 9);
console.log(result);

除了您返回 result.push(i, j) 的结果之外,您的代码实际上是正确的,其中 returns 数组的长度。

使用result.push(i, j);然后return result;

而不只是 return result.push(i, j);

考虑将问题分解成更小的部分 -

  • t 生成唯一的数字组合
  • a 通过生成器搜索第一个有效解决方案

function* t(n, i = 0, p = [])
{ if (p.length >= 2)
    yield p
  else if (i >= n.length)
    return
  else
    ( yield* t(n, i + 1, [...p, n[i]])
    , yield* t(n, i + 1, p)
    )
}

function a(n, q)
{ for (const [a, b] of t(n)) // <- step thru t
    if (a + b == q)          // <- simple condition
      return [a, b]          // <- solution
}

const result =
  a([2,7,11,15], 9)

console.log(result)

输出-

[2, 7]
如果无法达到答案,

a 将 return undefined