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

89
Vistas
undefined output in while loop w/array using Nth root equation javascript

I'm trying to write this code for an after effects expression that will move an object a calculated x distance over n number of frames. The movement over each frame is parabolic rather than linear, and so I'm using the nth root code to determine how much the object should move over each frame. I'm putting each of the nth roots into an array to access later when setting the positions for each move.

I'm still learning javascript mainly for AE, so please bear with me if there are things in here I don't fully understand. I think I understand, which is why I'm not sure I'm getting the undefined output for certain n values. Here's the code:

//get Nth root
function nthroot(x, n) {
  ng = n % 2;
  if ((ng == 1) || x < 0)
    x = -x;
  var r = Math.pow(x, 1 / n);
  n = Math.pow(r, n);

  if (Math.abs(x - n) < 1 && (x > 0 === n > 0))
    return ng ? -r : r;
}

distance=1515; //will be determined by another portion of the AE expression
frames=6; //will be set by expression control in AE
const myArray = [];
let i = 1;
while (i <= 6) {
  myArray.push(nthroot(distance,i++));

}

console.log(myArray);
document.getElementById("demo2").innerHTML = myArray

I put it into a fiddle here. What am I doing wrong? Thanks in advance for any help!

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

0

Your "nthroot" function doesn't return values consisistently: if you look at the end of your function you can find this part:

if (Math.abs(x - n) < 1 && (x > 0 === n > 0))
   return ng ? -r : r;

if you notice, you are returning a value only if the condition in the if statement is fullfilled, otherwise you are not returning any value. In JavaScript, a function that doesn't return any value returns "undefined" instead.

In other words, when

Math.abs(x - n) < 1 && (x > 0 === n > 0)

is true, you are returning either "r" or "-r", but when the condition is false you aren't returning any value, so the function returns "undefined".

You have to handle the false case.

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