Sparse Arrays in JavaScript
A common misconception in JavaScript is the assumption that arrays are contiguous, meaning that they contain all elements from index 0 to their current length. However, this is not the case: JavaScript arrays are sparse.
When an element is accessed or set using an index that is greater than the current length, an empty slot is created and the array is extended to the appropriate size. For example, if array[Date.getTime()] is used to set a value, the array will be extended to contain empty slots from index 0 to the current time, even though these slots will not be used.
Hash-Table Implementation
Sparse arrays are implemented as hash tables internally. Keys, which can be integers, strings, floats, or other objects, are converted to strings using toString() before being added to the hash. This allows for a flexible indexing system.
Test Example
To confirm the sparse nature of arrays, consider the following test code:
var array = []; array[0] = "zero"; array[new Date().getTime()] = "now"; array[3.14] = "pi"; for (var i in array) { alert("array[" + i + "] = " + array[i] + ", typeof(" + i + ") == " + typeof(i)); }
This code will display:
array[0] = zero, typeof(0) == string array[1254503972355] = now, typeof(1254503972355) == string array[3.14] = pi, typeof(3.14) == string
The for...in syntax iterates over the defined indices, demonstrating that the array is extended with empty slots when accessing or setting elements with non-sequential indices.
Browser Differences
Different browsers handle sparse arrays in a similar manner, with arrays implemented as hash tables. However, it's important to consider the use of sparse arrays when dealing with very large indices, as this can impact memory consumption and performance.
The above is the detailed content of Are JavaScript Arrays Really Contiguous?. For more information, please follow other related articles on the PHP Chinese website!