JS for循环中的for循环,我猜是作用域问题 [英] JS for loop in for loop, problem with scope I guess

查看:37
本文介绍了JS for循环中的for循环,我猜是作用域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入是数组INTS[11,2,7,8,4,6]和整数s 10,函数是输出一个数组,数组中的两个数字来自整型数,这两个数的和首先是10。所以这里的输出应该是[2,8],因为2+8=10。为什么它输出空数组?ArrResults是在嵌套的for循环中更新的,那么它为什么不像这样显示在最后一个返回语句之后呢?

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
function sumPairs(ints, s) {
  let arrResults = [];
  let sumOfTwo;
  for (i = 0; i < ints.length; i++) {
    for (j = 0; j < ints.length; j++) {
      sumOfTwo = ints[i] + ints[j];
      if (sumOfTwo === s) {
        arrResults.push(ints[i]);
        arrResults.push(ints[j]);
        break;
      }
    }
    if (arrResults !== []) {
      break;
    }
  }
  return arrResults;
}

console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));

推荐答案

一个数组与另一个数组的比较错误(没有相同的对象引用)

a = []
b = []

a === b // false

// other example

a = []
b = a

a === b // true

用于检查长度,

a = []
a.length // 0

即使在使用循环的情况下,也可以使用几乎是二次的n?时间复杂度

i = 0; i < array.length - 1
j = i + 1; j < array.length

哪个大于n的一半,但为二次

您可以对已看到值的对象进行单循环

此方法查找特定和的数组的第一对。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
function sumPairs(ints, s) {
    const needed = {};

    for (const value of ints) {
        if (needed[value]) return [s - value, value];
        needed[s - value] = true;
    }
}

console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));

这篇关于JS for循环中的for循环,我猜是作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆