How to use array length in Javascript
Description
The number of items in an array is stored in the length
property.
Example
var colors = ["red", "blue", "green"]; //creates an array with three strings
var names = []; //creates an empty array
console.log(colors.length); //3
console.log(names.length); //0
/*www . j a v a2 s .c o m*/
var names = new Array();
console.log(names.length);//0
The code above generates the following result.
Note
Array length in Javascript is not read-only.
By setting the length property, you can easily remove items from or add items to the end of the array.
var colors = ["red", "blue", "green"]; //creates an array with three strings
colors.length = 2;// www . ja v a 2 s.com
console.log(colors[2]); //undefined
console.log(colors.toString());
colors = ["red", "blue", "green"]; //creates an array with three strings
colors.length = 4;
console.log(colors[3]); //undefined
console.log(colors.toString());
The code above generates the following result.
Example 2
We can use length property to add items the end of an array.
The last item in an array is at position length - 1, so the next available open slot is at position length.
var colors = ["red", "blue", "green"]; //creates an array with three strings
colors[colors.length] = "black"; //add a color (position 3)
console.log(colors.toString());
colors[colors.length] = "brown"; //add another color (position 4)
console.log(colors.toString());
The code above generates the following result.
Example 3
var colors = ["red", "blue", "green"]; //creates an array with three strings
colors[99] = "black"; //add a color (position 99)
console.log(colors.length); //100
The code above generates the following result.