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

103
Visualizações
How to Use If in Loop to Return Message for No Results

Purpose: This allows you to choose a target number and then will identify two numbers from the array that sum to be the target number.

Question: How do I add a message when there are no two numbers in the array that sum to be the target number?

What I've tried: Tried doing else with a console.log message when result === 0, also tried when result === [], and result === [0]. Tried doing another if statement. I think I am getting the syntax and/or placement wrong.

Code:

const twoSum = (array, target) => {
    let result = [];
    for (i = 0; i < array.length; i++) {
        if(array[i] > target) {
            continue;
        }
        if(array.includes(target - array[i])) {
            result.push(array[i]);
            result.push(target - array[i]);
            break;
        }
        if(result.length < 1){
            console.log("The array does not have two numbers that sum to equal your target value.")
            break;
        }
    }
    return result;
};
let array = Array.from({length: 10000}, () => Math.floor(Math.random() * 10000));
const target = 2;
console.log(twoSum(array, target));
about 4 years ago · Juan Pablo Isaza
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