An array in JavaScript is a simple zero-level structure. array.length returns n + 1 , where n is the maximum index in the array.
Here's how it works: when you assign the 90th element and the length of this array is less than 90, it expands the array to 90 and sets the value of the 90th element. All missing values ββare interpreted as null .
If you try the following code:
var a = []; a[21] = {}; a[90] = {}; a[13] = {}; console.log(JSON.stringify(a));
You will get the following JSON:
[NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, {}, NULL, NULL, NULL, NULL, NULL, NULL, NULL, {}, NULL, NULL , NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, {}]
In addition, array.length not a read-only value.
If you set the length value to less than the current one, the size of the array will be resized:
var arr = [1,2,3,4,5]; arr.length = 3; console.log(JSON.stringify(arr));
If you set the length value to more than the current one, then the array will also be expanded:
var arr = [1,2,3]; arr.length = 5; console.log(JSON.stringify(arr));
If you need to assign such values, you can use JS objects.
You can use them as an associative array and assign any key-value pairs.
var a = {}; a[21] = 'a'; a[90] = 'b'; a[13] = 'c'; a['stringkey'] = 'd'; a.stringparam = 'e'; // btw, a['stringkey'] and a.stringkey is the same console.log(JSON.stringify(a)); // returns {"13":"c","21":"a","90":"b","stringkey":"d","stringparam":"e"} console.log(Object.keys(a).length); // returns 5