JavaScript minimalist tutorial iii: arrays

  • 2020-03-30 04:10:18
  • OfStack

Reading this article requires programming experience in other languages.

In JavaScript, arrays are objects (not linearly allocated memory).

Create an array with array literal:


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

An array has a property length (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:


var myArray = [];
myArray.length; // 0
myArray[1000000] = true;
myArray.length; // 1000001

We can directly modify length:

Changing length will not result in more space being allocated
Length is reduced and all attributes with subscripts greater than or equal to length are removed
Since arrays are also objects, you can use delete to delete elements in an array:


delete number[2];
number[2] === undefined;

Removing an element from an array like this leaves a void.

JavaScript provides a set of methods for arrays that are placed in array.prototype (I won't go into details here).


Related articles: