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

116
Vistas
My math.pow is return NaN when I call it on an array with numerical values. How do I get the square of an array element

I have a function with an array of numbers, I want to square it but I want them in the array box like [4,9,16] Each time i try to do that, it throws back a NAN output in the console. The numbers come back listed as in a straight line.

digit = (num) => {
  let digits = String(num).split('').map(Number);
  for (let i = 0; i < digits.length; i++) {
    let square = Math.pow(digits, 2);
    console.log(square);
  }
};
digit(234);

output : NaN

digit = (num) => {
  let digits = String(num).split('').map(Number);

  for (let i = 0; i < digits.length; i++) {
    let square = Math.pow(digits[i], 2);
    console.log(square);
  }
};
digit(234);

output : 4 9 16

Is it possible to have my output as [4,9,16]?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

What you want to do here is to modify the array in place, so you need to assign the result of Math.pow() to each element of the array.

digit = (num) => {
  let digits = String(num).split("")
  .map(Number);
  for(let i = 0; i < digits.length; i++) {
    digits[i] = Math.pow(digits[i], 2);
  }
  console.log(digits);
};
digit(234);

After the for loop is done, then each array item will be squared.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Math.pow() expects two inputs, both of which should be numbers (not arrays)

You need to loop through your digits, and push the values to an array.

Something like this:

function digit(num) {
    let digits = String(num).split('')
    .map(Number);
    let square = [] // Define an empty array outside the loop
    for(let i = 0; i < digits.length; i++){
        square.push(Math.pow(digits[i],2)); //Push each value to the loop
    }
    return square; //Return the modified array after the loop
}

console.log(digit(234)); //Outputs [4, 9, 16]
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