An array is collection of similar kind of data elements which can store same data types and we can not store some of int and some of float data types in Array.
2. Array Definition
An array is collection of similar kind of data elements which
can store same data types and we can not store some of int
and some of float data types in Array.
Traditionally an array is considered to be a collection of
homogeneous elements, which means that it cannot contain
dissimilar elements.
But JavaScript does not follow this concept.
A JAVASCRIPT ARRAY CAN CONTAIN HETROGENEOUS
ELEMENTS
Thus we can say that arrays in JavaScript are similar to
structure of C language except that they are accessed using
an index.
3. Creating An Array
We can create an array in 2 ways:
1. Using Array Literal
2. Using Array Constructor
4. Array Literals
Array literals are written using [ ]
containing array elements separated with
commas
Syntax:
var <array name>=[value,value,. . . ];
Example:
var nums=[2,5,8,3,9];
var colors=[“red”,”green”,”blue”];
5. Array Literals
Another way of using Array Literals is that we can
leave the [ ] empty and fill values afterwards.
Example:
var num=[ ]; /* declares the array */
num[0]=2; /* initializes it */
num[1]=5;
num[2]=8;
num[3]=3;
num[4]=9;
6. Creating Array Using Constructor
Since in JavaScript arrays are objects we can use
constructors also to create an array.
There are 3 versions of the constructor
1. Array( )
2. Array(size)
3. Array (initializer list)
7. Creating Array Using Constructor
The first constructor does not take any argument and
creates an empty array .
Elements may be added later
Example:
var colors=new Array( );
colors[0]=“red”;
colors[1]=“green”;
colors[2]=“blue”;
8. Creating Array Using Constructor
The second constructor takes an integer as argument
and creates an array of that size.
Example:
var colors=new Array(3);
colors[0]=“red”;
colors[1]=“green”;
colors[2]=“blue”;
9. Creating Array Using Constructor
The third constructor takes list of values as argument
and sets array elements with it.
Example:
var colors=new Array(“red”,”blue”,”green”);