Introduction to Arrays in JavaScript
JavaScript arrays are used to store multiple values in a single variable. An array in JavaScript can hold different elements We can store Numbers, Strings and Boolean in a single array. Also arrays in JavaScript are dynamic in nature, which means its size can increase or decrease at run time.
Syntax –
Use the following syntax to create an Array object −
var fruits = [ "apple", "orange", "mango" ]; var fruits = new Array( "apple", "orange", "mango" ); // another way but not prefered
Access the Elements of an Array –
You access an array element by referring to the index number. This statement accesses the value of the first element in cars:
var cars = ["Saab", "Volvo", "BMW"]; var name = cars[0];
Access the Full Array –
With JavaScript, the full array can be accessed by referring to the array name:
var cars = ["Saab", "Volvo", "BMW"]; document.write("<h2>"+cars[i]+"</h2>");
The length Property –
The length property of an array returns the length of an array (the number of array elements).
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // the length of fruits is 4
Looping Array Elements –
The safest way to loop through an array, is using a “for” loop:
var fruits, text, fLen, i; fruits = ["Banana", "Orange", "Apple", "Mango"]; fLen = fruits.length; text = "<ul>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>";