Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Activity Forums Adobe After Effects Expressions Unexpected result with a multi dimensional array in a For loop

  • Unexpected result with a multi dimensional array in a For loop

    Posted by Jamie Bradshaw on September 22, 2011 at 12:08 pm

    Any idea why the code below returns:
    0,2,4,0,2,4,0,2,4

    and not:
    0,0,0,1,2,3,2,4,6

    Many thanks

    getPropertyArrayFromString();

    function getPropertyArrayFromString(str_1) {
    n_1 = 3;
    n_2 = 3;
    tArray_1 = new Array();
    pArray_1 = new Array();
    for(n_3=0; n_3<n_1; n_3++) {
    for(n_4=0; n_4<n_2; n_4++) {
    tArray_1[n_4] = n_3 * n_4;
    }
    pArray_1[n_3] = tArray_1;
    }
    return(pArray_1);
    }

    JimJam•Graphics
    https://www.jimjamgraphics.com/

    Jamie Bradshaw replied 14 years, 7 months ago 2 Members · 4 Replies
  • 4 Replies
  • Dan Ebberts

    September 22, 2011 at 1:47 pm

    I’d try initializing tArray_1 before the inner loop:

    tArray_1 = [];

    I would expect [[0,0,0],[0,1,2],[0,2,4]]

    Dan

  • Jamie Bradshaw

    September 22, 2011 at 1:52 pm

    Thanks Dan.

    As always it seems obvious as soon as someone much more clever points it out to you! 😉

    JimJam•Graphics
    https://www.jimjamgraphics.com/

  • Dan Ebberts

    September 22, 2011 at 2:04 pm

    I think there’s a better way. What was happening was that each element of pArray_1 was getting a pointer to tArray_1 instead of the data in the array, so at the end of the routine pArray_1 consisted of three pointers to tArray_1, which had the last values. I think the correct way to fix this is to use slice() to get the data from the array, like this:

    pArray_1[n_3]= tArray_1.slice();

    Dan

  • Jamie Bradshaw

    September 22, 2011 at 2:31 pm

    Ah yes, that makes sense. Thanks again Dan!

    JimJam•Graphics
    https://www.jimjamgraphics.com/

We use anonymous cookies to give you the best experience we can.
Our Privacy policy | GDPR Policy