Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda