0

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!

KevinHaus
  • 1
  • 2

1 Answers1

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.

Picchio
  • 425
  • 1
  • 7
  • That helps to know. I did some searching and simplified the whole thing and now it works fine:```distance=1515; frames=6; const myArray = []; let i = 1; while (i <= frames) { myArray.push(Math.pow(distance,1/i++)); } console.log(myArray);``` I just removed the nth root function and put "Math.pow(distance,1/i++)" in for what is pushed. Thank you! – KevinHaus Oct 29 '21 at 15:41