Search code examples
javascriptarraysvariable-length

Are variable length arrays possible with Javascript


I want to make a variable length array in Javascript.

Is this possible. A quick google search for "Javascript variable length array" doesn't seem to yield anything, which would be surprising if it were possible to do this.

Should I instead have a String that I keep appending to with a separator character instead, or is there a better way to get a varible length array-like variable.


Solution

  • Javascript arrays are not fixed-length; you can do anything you want to at any index.

    In particular, you're probably looking for the push method:

    var arr = [];
    arr.push(2);            //Add an element
    arr.push("abc");        //Not necessarily a good idea.
    arr[0] = 3;             //Change an existing element
    arr[2] = 100;           //Add an element
    arr.pop();              //Returns 100, and removes it from the array
    

    For more information, see the documentation.