Array
JavaScript arrays are different from arrays in other languages. Traditionally,
an array is considered to be a collection of homogeneous items. It means
an array cannot contain dissimilar items.
JavaScript does not follow this concept at all. A javaScript array may
contain heterogeneous items. These arrays are similar to structure
variables, except that they can be accessed randomly with the array name
and index. That is why javaScript arrays are sometimes called associative
arrays.
Array Literal:
An array variable may be created by assigning an array literal to it. An array
literal is written using square brackets with array elements separated by
commas (,) as follows:
Var arrName = [element0, element1, …. , elementn ];
e.g.,
var odds = [1, 3, 5, 7];
var vowels = [‘a’, ‘e’, ‘I’, ‘o’, ‘u’];
var colors=[“red”, “green”, “blue”, “yellow”];
var flag= [true, false];
var empt=[];
Accessing elements from Array:
Elements are accessed using the array name and the index of the element
written within square brackets.
For example, colors[2], odds[3], vowels[1], etc.
The array index starts with 0.
Santosh Kumar Jha, AssistantProfessor, LNMI, Patna Page 1
So, flag[0] is true, odds[3] is 7.
A javaScript Array literals may contain undefined
elements:
e.g.,
var colors =[“red”, , , “green”, “blue”];
var len=[Link];
len=5
colors[0] ………colors[4]
Array with heterogeneous elements:
Var emp = [“Janak”, 24, false, 40000];
emp[0] = “Janak”;
emp[1]=24;
emp[2]=false;
emp[3]=40000;
JavaScript arrays are dynamic in nature:
It means that elements can be added and deleted as and when required.
e.g.,
var odd = [ 1, 3, 5, 7];
odd[4] = 9;
odd[[Link]] = 11;
Santosh Kumar Jha, AssistantProfessor, LNMI, Patna Page 2