Search code examples
javascriptarrayspointersdefined

javascript pointers array or #define for abbreviation


I have a multi-dimensional array with different types of variables, like this:

array = [  [[file, name, visible], [ArrayPoint, ArrayOther], ...],  [[file2,...], ..]  ]

now in my code multiple times I have to call (for example) an Array() of points which is located in myArray [X] [1] [0].

I wanted to know if there was the possibility of creating definitions or pointers to the array position to shorten the code, because often I do not remember the variable positions.

// access the value at the address available in pointer
var *pointArray = &myArray[X][1][0];

// my code
*pointArray.push(pint_x, point_y);

============== VS ==============

myArray[X][1][0].push(pint_x, point_y);

thank you very much!! and good evening.

by Marco.


Solution

  • If you do

    var pointArray = myArray[X][1][0];
    

    It will make a copy of the reference to the array at myArray[X][1][0]. Therefore, any subsequent mutations to the elements of pointArray will also change the elements of myArray[X][1][0].

    Note that reassigning a new value to pointArray as a whole would not effect myArray[X][1][0], since that would only make pointArray store something else.

    Assignments do not copy/clone objects in JavaScript, they only make the variable on the left-hand side reference the same object as what's on the right-hand side.

    var outer = [[0,1,2],[3,4,5]];
    var inner = outer[1];
    
    inner.push(6);
    console.log(JSON.stringify(outer));
    
    inner = [];
    console.log(JSON.stringify(outer));