Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variable length arrays possible with Javascript

Tags:

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.

like image 691
Ankur Avatar asked Mar 24 '10 02:03

Ankur


People also ask

Can you make an array of variables JavaScript?

JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.

Can you declare an array with a variable size?

You can define variable-size arrays by: Using constructors, such as zeros , with a nonconstant dimension. Assigning multiple, constant sizes to the same variable before using it. Declaring all instances of a variable to be variable-size by using coder.

Does Java support variable length arrays?

In Java, Arrays are of fixed size. The size of the array will be decided at the time of creation. But if you still want to create Arrays of variable length you can do that using collections like array list.

How long can JavaScript arrays be?

What exactly is the JavaScript Array length property. By definition, the length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. The value of the length is 232. It means that an array can hold up to 4294967296 (232) elements.


1 Answers

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.

like image 146
SLaks Avatar answered Sep 27 '22 20:09

SLaks