The number of items in an array is stored in the length
property.
The length
property sets or gets the number of elements in an array.
length |
Yes | Yes | Yes | Yes | Yes |
To get the length of an array.
var len = array.length;
To set the length of an array:
array.length = newLength;
Returns the number of elements in the array object.
The following code shows how to access the length of an array.
//creates an array with three strings
var colors = [ "A", "B", "C" ];
//creates an empty array
var names = [];
console.log(colors.length); //3
console.log("<br/>");
console.log(names.length); //0
The code above generates the following result.
By setting the length
property, you can remove
or add items to the end of the array.
//creates an array with three strings
var colors = ["A", "B", "C"];
colors.length = 2;
console.log(colors[2]); //Undefined
//add a color (position 99)
colors[99] = "D";
console.log(colors.length); //100
The code above generates the following result.