Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do array sizes work in Javascript

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)

like image 788
rubixibuc Avatar asked Jun 03 '11 20:06

rubixibuc


People also ask

How does array size work?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

Do array sizes start at 0 or 1?

Arrays in Java use zero-based counting. This means that the first element in an array is at index zero.

Is array size fixed in JavaScript?

They have fixed size.

What does array length 1 mean in JavaScript?

length -1 means, specifically the -1 part. When using a for loop over an array we have something like this: for (i = 0; i < array.


1 Answers

Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.

It is also more common to use the simpler [] syntax.

var arr = ['something', 34, 'hello'];

You can set (or replace) a specific index by using brackets:

arr[0] = "I'm here replacing whatever your first item was";

You can add to the end by using push:

arr.push('add me');

There may be faster performance in some browsers if you do it like this instead:

arr[arr.length] = 'add me';

You can add something at any index.

You can remove an item completely using splice:

arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)
like image 125
Brett Zamir Avatar answered Oct 01 '22 17:10

Brett Zamir