【问题标题】:If statement not returning anything inside of two for loopsIf 语句在两个 for 循环内不返回任何内容
【发布时间】:2020-09-25 07:54:31
【问题描述】:

我试图在 if 语句中返回一个数组,但没有返回任何内容。当我 console.log( [ i, j ] ) 时,它工作正常。

const twoSum = function(nums, target) {
   for (let i = 0; i < nums.length; i++) {
       for (let j = 0; j < nums.length; j++) {
           if (nums[i] + nums[j] === target) {
               return [ i, j ];
           }
       }
   }
};

twoSum([ 2, 7, 11, 15 ], 9);

我知道这不是解决这个问题的最有效方法,但我只是在学习基础知识,我很困惑为什么这没有返回任何东西。

【问题讨论】:

  • 您没有对调用twoSum 的返回值做任何事情。你试过了吗,console.log(twoSum([2,7,11,15], 9))
  • 一切正常。
  • 您需要在页面中使用 id 或类选择器将其输出。尝试使用document.write(twoSum([ 2, 7, 11, 15 ], 9)); 调试它只是为了在页面上显示结果,如果结果在那里,那么它工作正常,只是还没有弯曲到任何选择器。
  • 尝试使用 console.log(functioncall)

标签: javascript if-statement return


【解决方案1】:

它应该返回[0, 1]。 如果要在控制台中显示结果,请尝试:

console.log(twoSum([ 2, 7, 11, 15 ], 9));

【讨论】:

    【解决方案2】:

    也许你可以这样写,这样更容易阅读。有两个 for 循环很难处理。如果我们知道数组只有正数,我们可以优化它。

      const twoSum = (nums, target) => {
        let found = null;
    
        nums.some((n, i) => {
          // here you figure where you are looking for.
          const lookingFor = target - n;
    
          const idx = nums.indexOf(lookingFor, i);
    
          if (idx !== -1) {
            found = [i, idx];
            return true;
          }
          return false;
        });
    
        return found;
      };
    
      console.log(twoSum([ 2, 7, 11, 15 ], 9));
    

    【讨论】: