Search code examples
javascriptadobeafter-effects

Adobe javascript object undefined after function


I'm trying to learn some javascript by making a script for adobe after effects cs6. However i got stuck and can't figure out why. Let me explain my problem.

at row 156, in the doMath function is where my problems start. I can't figure out why the copyarray makes the layers variable undefined. it's not only the copyarray function that makes the variable undefined. The getSmallest and the getLargest does it aswell.

Some data from my code that i printed out (Might be useful).

Layername    +Y max="80" target="4" inverted
axis         Y
maxValue     80
target       4
positive     true
inverted     true

http://pastebin.com/tWQs4mf8 <--- my code

function doMath(layers){
    for(i=0;i!=layers.length;i++)
    {
        if(layers[i].axis=="X")
        {
            layers[i].convertedData=layers[i].Xdata;
        }
        else
        {
            layers[i].convertedData=layers[i].Ydata;
        }
        alert(layers[i])                                    //Shows on the alert "Object object"
        var copy = copyArray (layers[i].convertedData);
        alert(layers[i]);                                   //Shows undefined
        var smallest = getSmallest(copy);
        var largest = getLargest (copy);
        var range = largest-smallest;
        $.writeln(smallest + " " + " " + largest + " " + range);                                                   
        if(layers[i].Positive==null)
        {
            var temp = getConverted(layers[i].convertedData,smallest,range,layers[i].maxValue,layers[i].inverted);
            layers[i].convertedData=temp;
        }
    }
};

function copyArray(a){
    var b = [a.length];
    for(i=0;i!=a.length;i++)
    {
        b[i] = a[i];
    }
    return b;
}

Since i'm very new to javascript a simple reason what's happening is very appreciated.


Solution

  • It's not making layers undefined, it's making layers[i] undefined.

    The problem is that you're using the global variable i in both loops. So when copyArray is done, i is set to layers.length. But the last element in layers is layers[layers.length-1].

    You should always use local variables, not global variables, unless you have a good reason to need the data to be visible in multiple functions. So you should write:

    for (var i = 0; i < a.length; i++)
    

    in your loops.