We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 15
CMSI CSS 22519 Nibe Sir, CM Dept. Polytechnic, Loni
Unit 2: Array, Function and String
Unit 2: Array, Function and String (14 Marks)
*Array:
JavaScript arrays are used to store multiple values in a single variable.
‘An array is a special variable, which can hold more than one value at a time.
Syntax:
var array_name = |item', item2,
Example
var cars = ["Skoda’, "Volvo", "BMW"};
JavaScript Arrays
Example (another way to declare an array)
var cars = [
"Skoda’,
"Volvo",
"BMW"
Ik
‘Scanned with CamScannerCMSI CSS 22519 Nibe Sir, CM Dept. Polytechnic, Loni
Unit 2: Array, Function and String
The following example creates an Array, and assigns values to it:
Example (new keyword is used)
var cars = new Array("Skoda’, "Volvo", "BMW");
JavaScript Arrays
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 name = cars{0];
Example
var cars = ["Skoda’, "Volvo", "BMW"};
document. getElementByld("demo').innerHTM& = cars(0};
JavaScript Arrays
JavaScript array elements are accessed using numeric indexes (starting from
0)
jemo">
‘Scanned with CamScannerCMSI CSS 22519 Nibe Sir, CM Dept. Polytechnic, Loni
Unit 2: Array, Function and String
Looping Array Elements
The safest way to loop through an array, is using for loop.
JavaScript Arrays
‘Scanned with CamScannerCMSI CSS 22519 Nibe Sir, CM Dept. Polytechnic, Loni
Unit 2: Array, Function and String
Adding Array Elements
The easiest way to add a new element to an array is using the push() method.
JavaScript Arrays
The push method appends a new element to an array.