Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are JavaScript arrays associative?

For instance, if I do a[1000000]=1; will it use memory for 1000000 elements or just for this one?

like image 901
Lem0n Avatar asked Apr 04 '10 20:04

Lem0n


People also ask

What is associative array in JavaScript with example?

An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.

What syntax is used to create an associative array in JavaScript?

An associative array is declared or dynamically createdvar arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets.

Are arrays growable in JavaScript?

Array objects grow and shrink dynamically and can have any JavaScript value.


2 Answers

In the ECMAScript standard (§15.4), the only special thing about array is that the length property is automatically updated (and a bunch of Array-specific prototype functions):

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1.
...
Every Array object has a length property whose value is always a nonnegative integer less than 232. The value of the length property is numerically greater than the name of every property whose name is an array index; ...

Other than that, an Array is just an Object, which means it can be treated as an associative array, although you shouldn't.


Nowadays the JS engines should detect whether the array is dense or very sparse and switch between using a linear or associative array internally. In your case, the JS engine won't allocate a million elements.

like image 110
kennytm Avatar answered Nov 07 '22 09:11

kennytm


Would 1,000,000 elements be created?

No, arrays are sparse, but their index will be persistent. EDIT: Actually, their sparseness would be implementation-specific, but keeping them sparse in case of a[1000000] = 1 would seem a logical thing to me.

var a = [1, 2, 3, 4];
var x = a[1]; // -> x := 2

delete a[1];
var y = a[1]; // -> y := undefined

a[9] = 10;
var y = a[8]; // -> z := undefined

Are JS arrays associative?

JavaScript arrays are a subset of associative arrays (in that indices have to be integers, as shown in KennyTM's answer. JavaScript objects are fully associative:

var o = { "key1": "value1", "key2": "value2" };
var i = "key2";
var v = o[i]; // -> v := "value2"
like image 26
Tomalak Avatar answered Nov 07 '22 11:11

Tomalak