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

180
Visualizações
Javascript multiply algorithm

I am trying to learn JavaScript arrays and algorithms and for loops. I am trying to make a function, that takes an array as a parameter, and has to multiply each number in the array with the next number. I can't seem to figure out what I am missing.

It just returns the array

function xNumbers (arr) {
    for (let i = 0; i < arr.lenght-1; i++) {
        var num1 = arr[i]
        var num2 = arr[i+1]
        var result;

        try {
            if (typeof (num1) == 'string' || typeof (num2) == 'string') {
                throw num1, "or", num2, "is not a number";
            } else if (num2 == 0) {
                throw 'Cant multiply with 0'
            } else {
                result = num1*num2
            }
                
            
        } catch (error) {
            console.log(error);
            result = NaN;

        } finally {
            arr[i] = result
        }
        
    }
    return arr
}

console.log(xNumbers([2,3,4,5]));
// expected output 6, 12, 20 - doesn't work
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you can use the following code.

function xNumbers (arr) {
    arr = arr.map(x => Number(x))
    result = new Array(arr.length -1)
    for (let i = 0; i < arr.length-1; i++) {
        result[i] = arr[i] * arr[i + 1]
    }
    return result
}

console.log(xNumbers([2,3,4,5]));

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