JavaScript Arrays
JavaScript Arrays
JavaScript Arrays
Dr. Sandhya P,
VIT Chennai
JavaScript Arrays
Array Object
Creating Arrays
Indexed Arrays
Multidimensional Arrays
Iterating over an Array
Adding Element to an Array
Removing Elements from an Array
Associative Arrays
Arrays and Strings
Dr. Sandhya P VIT Chennai
3
Array Object
Arrays are reference types.
Array is a variable that holds multiple values.
In JavaScript all arrays are instances of global Array object
(wrapper class).
length is an important property of Array
Creating Arrays
Arrays can be created in two ways:
Using constructors of Array (There are 3 versions of constructors)
Creating using array literal
Examples:
var arr=new Array();
var arr=new Array(10);
var arr=new Array(“Mon”,”Tue”,”wed”);
Indexed Arrays
Normal arrays are indexed.
The index starts from zero.
Each item can be accessed based on its position or index in the
array.
Indexed Arrays
var arr = [“Kevin”, “Eric” , “Jacob” , 20 , true];
document.write(arr[0]); //Kevin
document.write(arr[1]); //Eric
document.write(arr[2]); //Jacob
document.write(arr[3]); //20
document.write(arr[4); //true
Multidimensional Arrays
Also called as jagged arrays.
They are array of arrays.
var student = [[“Kevin”,90,”CSE”] , [“Eric”,40,”IT”] ,
[“Jacob”,60,”ECE”]];
document.write(student[1][0]); //Eric
document.write(student[2][2]); //ECE
Detecting Arrays
Using Index
concat()
Array
Manipulating the length of the array
If the last element needs to be deleted decrement the length of the
array by 1.
Using methods of Array
pop – Deletes the last element of the array
shift – Deletes the first element of the array
slice()
Associative Arrays
Associative arrays are arrays with key/value pairs.
It does not have numeric index.
The keys are used to access or modify the values.
var stud={“regno”:”19MIA1234”,”name”:”kevin”}
regno and name are keys
19MIA1234 and Kevin are respective values
Associative Arrays
Associative arrays do not support length property.
Hence we use a for..in loop
REFERENCE
Alexei White, JavaScript Programmer’s Reference, Wrox, ISBN:978-
81-265-2363-4