Are JavaScript arrays associative?

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

+6
javascript arrays associative
source share
4 answers

In the ECMAScript standard (& section; 15.4), the only feature of the array is that the length property is automatically updated (and the bunch of prototype functions specific to Array):

Array objects provide a special approach to a specific class of property names. The name of the P property (as a String value) is the index of the array if and only if ToString(ToUint32( P )) is equal to P and ToUint32( P ) not equal to 2 32 -1.
...
Each Array has a length property, whose value is always a non-negative integer less than 2 32 . The value of the length property is numerically greater than the name of each property whose name is the index of the array; ...

Furthermore, an array is just an object, which means that it can be considered as an associative array, although you shouldn't .


Currently, JS engines must determine if the array is dense or very sparse, and switch between a linear or associative array inside. In your case, the JS engine will not allocate a million elements.

+8
source share

Will 1,000,000 items be created?

No, arrays are sparse, but their index will be constant. EDIT: Actually, their sparseness would be implementation-specific, but keeping them sparse in the case of a[1000000] = 1 would seem logical 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 (these indices must have integers, as shown by KennyTM . JavaScript objects are fully associative:

 var o = { "key1": "value1", "key2": "value2" }; var i = "key2"; var v = o[i]; // -> v := "value2" 
+7
source share

In some cases, you can use the object literal as a kind of "associative arai":

 var object = { "first": "1", "second": "2", "third": "3", "fourth": "4" }; object.fifth = "5"; object.["sixth"] = "6"; 

But it has its limitations ... There is no magic parameter "length", and you will not have access to the methods that each array has.

+1
source share

JS arrays automatically grow. Setting [100] to 1 empty array will fill the first 99 "undefined" elements.

0
source share

All Articles