The arrays are, as in other languages, widely used in JavaScript but unlike with those languages, in JS arrays can contain any type of data.
The data inside the arrays may be of different types at the same time; let say the first data may be a number, then a string, followed by an object etc... The arrays are also dynamically sized and they grow or shrink as new data is being added or old taken out.
An array may be created by using the Array constructor or by using array literal notation as shown below:
Array Constructor:
var colors = new Array(); // array
var colors = new Array("blue","green","brown"); // array with 3 colors
var colors = new Array(5); // array with 5 items
Array Literal:
var colors = [];
var colors = ["blue","green","brown"];
Array Indexing
The items within arrays are indexed with numbers that reflect their respective positions, starting with "0". For instance the first item from above example may be addressed as colors[0] which would give "blue" as result.
To change the value of the first item from "blue" to "gray", same indexing rule may be applied:
var colors = new Array("blue","green","brown");
colors[0] = "gray";
Array Length
To verify the length (number of items) in an array, the length property may be used, as shown here:
var cars = ["Volvo","KIA","Ford"];
alert(cars.length); // result = 3
The same property may be used to modify the length of an array, let say:
cars.length = 4; // adds an item "undefined" to the last spot
cars.length = 2; // removes the last item from array above
The maximum number of items an array can obtain is 4294967295 but even approaching to a number of such magnitude will create script timeouts so it's better to limit it to more reasonable values.
Comments
No comments have been made yet.
Please login to leave a comment. Login now