Javascript - Array

4. Array

All array objects are linked to Array.prototype. You can contain any mix types in a single array.

var arr = ['string', 98.4, true, null, undefined, NaN, ['a', 5], {obj: true}];

arr.construtor == Array // true

4.1 Length

The length of an array is equal to the max index +1.

var myArray = []; // length == 0

myArray[100] = true; // length == 101

The length of an array could be set.

var arr = [1, 2, 3, 4];

arr.length = 3; // arr == [1, 2, 3]

Two way to append new element to an array.

arr[arr.length] = 5;

arr.push(5);

Add a number key to an array will plus its length.

var arr = [1, 2, 3];

arr["a"] = 4; // arr.length == 3;

arr["3"] = 4; // arr.length == 4

4.2 Delete

var arr = [1, 2, 3, 4];

delete arr[2]; // arr == [1, 2, undefined, 4,]

arr.splice(1, 1); // arr == [1, undefined, 4]