Javascript Arrays
Javascript Arrays
Loops
We discussed the concept of flow control using
the “if” and “switch” structures
x=1;
Initial count
while ( x < 6000 ) { Condition Operation
document.write ( x ) ;
x=x+1;
} for ( x = 1 ; x < 6000 ; x = x + 1 ) {
document.write ( x ) ;
}
6
Arrays
fruit[ 0 ]
Square
Identifier Index
bracket
13
student1 = “Waseem” ;
student2 = “Waqar” ;
student3 = “Saqlain” ;
student4 = “Daanish” ;
document.write( student1 ) ;
document.write( student2 ) ;
document.write( student3 ) ;
document.write( student4 ) ;
15
The ‘assignment’
operator
Length of the
new instance of
This is the parent object (or class) of ‘Array’
the new instance
An Object
19
‘Instances’ of an Object
20
21
All instances
of an object are objects
themselves!
‘Property’ Values of the Instances May Differ
22
23
Array Identifiers
name[ 5 ] = “bhola” ;
number = 5 ;
name[ number ] = name[ 5 ] ;
for ( x = 0 ; x < 10 ; x = x + 1 ) {
y[ x ] = x * x ;
}
26
a = new Array( 9 ) ;
b = new Array( 13 ) ;
b[ 0 ] = 23.7 ;
b[ 1 ] = “Bhola Continental Hotel”;
b[ 2 ] = a ;
The ‘length’ Property of Arrays
28
‘d’ is an ‘length’ is a
instance of the property of
‘Array’ object the object ‘d’
d = new Array ( 5 ) ;
document.write( d.length ) ;
The ‘length’ Property of Arrays
29
x = new Array ( 10 ) ;
x = new Array ( 4 ) ;
x[ 0 ] = “Waseem” ; Saqlain
x[ 1 ] = “Waqar” ; Shoaib
x[ 2 ] = “Saqlain” ; Waqar
x[ 3 ] = “Shoaib” ;
Waseem
x.sort( ) ;
for ( k = 0 ; k < x.length; k = k + 1 ) {
document.write( x[ k ] + “<BR>” ) ;
}
31
x = new Array ( 4 ) ;
x[ 0 ] = “Waseem” ; Waseem
x[ 1 ] = “Waqar” ; Waqar
x[ 2 ] = “Saqlain” ; Shoaib
x[ 3 ] = “Shoaib” ; Saqlain
x.sort( ) ;
x.reverse( ) ;
for ( k = 0 ; k < x.length; k = k + 1 ) {
document.write( x[ k ] + “<BR>”) ;
}
Let’s Now Do a More Substantial 34
Example
Develop a Web page that prompts the user for 10
words, and then displays them in form of a list in
two different ways:
2. Prompt the user and read the user input into the
elements of the array
<HEAD>
<TITLE>Sort Ten Words</TITLE>
<SCRIPT>
//JavaScript Code
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
41
2. Prompt the user and read the user input into the
elements of the array
2. Prompt the user and read the user input into the
elements of the array
1. Declare the array that will be used for storing the words
2. Prompt the user and read the user input into the elements
of the array
words.sort( ) ;
Take a look –
https://youtu.be/kPRA0W1kECg