Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
JavaScript variable returns undefined throughout if statements and loops

I'm trying to do the basic twoSum question from leetcode. My nums array comes back as undefined throughout this function, and I'm totally lost as to why. I'm sure it's obvious, but I'm having a hard time even troubleshooting it, because no matter where I put console logs in this function, it always says that nums is undefined.

const nums = [2, 7, 11, 15];
const target = 9;

function twoSum() {
    if (nums.length > 0) {
        while (nums === Number) {
            for (let i = 0; i < nums; i++) {
                for (let k = 0; k < nums; k++) {
                    if (i + k == target) {
                        console.log([i, k]);
                    } else {
                        console.log("no result");
                    }
                }
            }
        }
    } else {
        console.log("Array is Empty");
    }
};

console.log(twoSum());

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to make the following changes in your code. It should fix your issue

  • No need for while (nums === Number) condition
  • replace i + k == target with nums[i] + nums[k] == target. As i and k are indexes not actual values in array
  • Don't use console.log("no result"); in else condition. Instead create a flag and check if it's false then do the console.log Otherwise it will console.log everytime nums[i] + nums[k] !== target.

const nums = [2, 7, 11, 15];
const target = 9;

let  flag = false;
function twoSum() {
  if (nums.length > 0) {
    for (let i = 0; i < nums.length -1; i++) {
      for (let k = 1; k < nums.length; k++) {
        if (nums[i] + nums[k] == target) {
        flag = true;
          console.log('indexes', [i, k], 'values', [nums[i], nums[k]]);
        }
      }
    }
    if (!flag) {
    console.log("No Result")
    }

  } else {
    console.log("Array is Empty");
  }
}

twoSum();

about 4 years ago · Juan Pablo Isaza Relatório

0

Assumed objective

Given an array of integers and a target, find any pairs of integers in the array whose sum matches the target.

Code Snippet

const nums = [2, 7, 11, 15];
const target = 9;

const twoSum = (tgt = target, arr = nums) => (
  arr.forEach(x => 
    arr.forEach(y =>
      x + y === tgt && console.log(x, y)
    )
  )
);

console.log('target = 9');
twoSum();

console.log('target = 4');
twoSum(4);

console.log('target = 30');
twoSum(30);

console.log('target = 55');
twoSum(100) || console.log('no matches');

Explanation

  • Iterate through the array with each item taken as x
  • Now, iterate again with each item taken as y
  • If the sum of x and y matches target, then console.log

NOTES

  • As seen in the test cases, same numbers may be considered twice. So, for target of 4 the code prints out 2 2.
  • This may be avoided by changing the limits of the outer and inner loops.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda