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

109
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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