Reading this article requires programming experience in other languages.
In JavaScript, arrays are objects (not linearly allocated memory).
Create an array through array literal:
The code copy is as follows:
var empty = [];
var numbers = [
'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine'
];
empty[1] // undefined
numbers[1] // 'one'
empty.length // 0
numbers.length // 10
The array has an attribute length (while the object does not) to indicate the length of the array. The value of length is the maximum integer attribute name of the array plus 1:
The code copy is as follows:
var myArray = [];
myArray.length; // 0
myArray[1000000] = true;
myArray.length; // 1000001
We can directly modify the length:
length is changed to not cause more space to be allocated
length is changed to smaller, and all attributes with subscript greater than or equal to length are deleted
Since arrays are also objects, you can use delete to delete elements in the array:
The code copy is as follows:
delete number[2];
number[2] === undefined;
This way deleting elements in the array will leave a hole.
JavaScript provides a set of array methods, which are placed in Array.prototype (I won't introduce it in detail here).