SlideShare a Scribd company logo
LOOPS AND ARRAYS
       Session 10
Objectives
   Describe while loop.
   Explain for loop.
   Describe do-while loop.
   Explain break and continue statements.
   Describe the methods of Array object.
What is a loop?
   Loop is a section of code in a program which is
    executed repeatedly, until a specific condition is
    satisfied.
   There are three type of loop structures:

             The while loop

          The do-while loop

              The for loop
The while loop
   The while loop executes a
    block of code as long as the
    given condition remains        Conditio
                                                false

    true.                             n



 Syntax:
                                         true
while (condition)
{                                  Execute
                                    body            Exit loop
  statement(s);                    of loop

}
The while loop: Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>while loop demo</title>
   <script language="javascript" type="text/javascript">
         var n=20;
         var i=0;
         document.write("Display the odd number <br>");
         while(i<=n)
         {
            if(i%2 == 0)
                  document.write(i + "t");
            i++;
         }
   </script>
   </head>
   <body>
   </body>
</html>
The do-while loop
   The do-while loop is similar to the
    while loop, but the do-while loop                 do

    evaluates the condition at the end of
    the loop. So that, the do-while loop           Execute
                                                    body
    executes at least once.                        of loop

 Syntax:
do                                          true
                                                    Conditio
                                                       n
{
  statement(s);                                            false

}while(condition);                                 Exit loop
The do-while loop: Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>while loop demo</title>
   <script language="javascript" type="text/javascript">
         var n=20;
         var i=0;
         document.write("Display the even number <br>");
         do
         {
            if(i%2 == 0)
                  document.write(i + "t");
            i++;
         } while(i<=n);
   </script>
   </head>
   <body>
   </body>
</html>
The for loop
 Syntax:
for(initialization; condition; increment/decrement)
{
  statement(s);
}
   The initialization is an assignment statement that sets the
    loop control variable, before entering the loop.
    The condition is a relational expression, which
    determines, when the loop will exit.
    The increment/decrement defines how the loop control
    variable changes, each time the loop is executed.
The for loop: Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>for loop demo</title>
   <script language="javascript" type="text/javascript">
         var n=20;
         var i=0;
         document.write("Display the even number <br>");
         for(i=0; i<n; i++)
         {
            if(i%2 == 0)
                  document.write(i + "t");
         }
   </script>
   </head>
   <body>
   </body>
</html>
break statement
   The break statement can be used in the switch-
    case and loop constructs. It is used to exit the
    loop without evaluating the specified condition.

    for(initialization; condition; increment/decrement)
    {
       ….
       if(condition)
           break;
       …
    }
    ...
break statement: Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Using break statement</title>
   <script language="javascript" type="text/javascript">
         var n = prompt("Enter the number n:");
         var i=0;
         for(i=2; i<n; i++)
         {
                  if(n % i == 0)
                  {
                           document.write(n + " is not a prime number.");
                           break;
                  }
         }
         if(i == n)
            document.write(n + " is prime number.");
   </script>
   </head>
</html>
continue statement
   The continue statement is mostly used in the loop
    constructs. It is used to terminate the current
    execution of the loop and continue with the next
    repetition by returning the control to the beginning of
    the loop.
        for(initialization; condition; increment/decrement)
        {
           ….
           if(condition)
               continue;
           …
        }

        ...
continue statement: Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>continue statement demo</title>
   <script language="javascript" type="text/javascript">
         var n=20;
         var i=0;
         document.write("Display the even numbers <br>");
         for(i=0; i<=n; i++)
         {
                  if(i%2 == 1)
                           continue;
                  else
                           document.write(i + "t");
         }
   </script>
   </head>
</html>
Single-dimensional arrays
   An array is a collection of values stored in adjacent
    memory locations. These array values are referenced
    using a common array name.
   The values of array are the same data type. These values
    can be accessed by using the subscript or index numbers.
    The index determines the position of element in the array
    list.
   In a single-dimensional array, the elements are stored in a
    single row in the located memory.
   In JavaScript, the first element has the index number zero.
                                                  Index
                                          Value
Declaring arrays
There are three ways to declaring an array:
 Using the Array object: declare an array by using the new
  operator, and then initialize the individual array elements:
    var arr = new Array(3);
    arr[0] = “Single”;
    arr[1] = “Married”;
    arr[2] = “Divorced”;
   Initialize the array variable at the time of declaration:
    var arr = new Array(„Single‟,‟Married‟,‟Divorced‟);
   Creates an array without using Array object:
    var arr = {„Single‟,‟Married‟,‟Divorced‟};
Single-dimensional arrays - Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Single-dimensional array</title>
         <script language="javascript" type="text/javascript">
            var arr = new Array("Lundi", "Mardi", "Mercredi", "Jeudi",
                  "Vendredi", "Samedi","Dimanche");
            document.write("The days in a week <br>");
            for(i=0; i<arr.length; i++)
               {
                  document.write(arr[i] + '<BR>');
               }
         </script>
   </head>
</html>
Multi-dimensional arrays
   A multi-dimensional array stores a combination of values of
    a single type in two or more dimensions.
   A two-dimensional array represents as rows and columns
    similar to a table.
   JavaScript does not directly support two-dimensional array.
    You can create two-dimensional array by creating an array
    of arrays. You first declare an array and then create another
    array to each element of the main array.
    var emp= new Array(3);
    emp[0] = new Array(„John‟,‟300‟);
    emp[1] = new Array(„David‟,‟400‟);
    emp[2] = new Array(„Richard‟,‟500‟);
Multi-dimensional arrays - Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Single-dimensional array</title>
      <script language="javascript" type="text/javascript">
         var emp = new Array(3);
         emp[0] = new Array('Huynh Bay','1900');
         emp[1] = new Array('Minh Thanh','900');
         emp[2] = new Array('Tan Hung','800');
         document.write('<table border=1> <tr> <th>Name</th>   <th>Salary</th>
                  </tr>');
         for(var i=0; i<emp.length; i++)
         {
            document.write('<tr>');
            for(var j=0; j<emp[i].length; j++)
               document.write('<td>' + emp[i][j] + '</td>');
            document.write('</tr>');
         }
         </script>
   </head>
</html>
Array methods
   An array is a set of values grouped together an identified by
    a single name. In JavaScript, an Array allows you to create
    arrays. It provides the length property that is used to
    determine the number of elements in an array.
   The various methods allow you to access and manipulate
    the array elements:
    - concat: combines one or more array variables.
    - join: joins all the array elements into a string.
    - pop: retrieves the last element of an array.
    - push: appends one or more elements to the end of an array.
    - sort: sorts the array elements in alphabetical order.
    - reverse: retrieves the elements from the last to the first index
    position.
    - toString: converts the array elements into string.
Array methods - Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Using method in array</title>
         <script language="javascript" type="text/javascript">
            var days = new Array('Monday','Tuesday','Wednesday');
            document.write('Number of days: ' + days.length + '<br>');
            document.write('The days: ' + days.join(', ') + '<br>');
            document.write('The days after adding more: ' +
                  days.push('Thursday','Friday','Saturday') + '<br>');
            document.write('The days after sorting:' + days.sort() + '<br>');
            document.write('The days after sorting in desceding order:' +
                  days.reverse() + '<br>');
         </script>
   </head>
</html>
for … in Loop
   The for…in loop is an extension of for loop. It enables you
    to perform specific actions on the array objects. The loop
    reads every element in the specified array and executes a
    block of code once for each element in the array.
   Example:
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Using method in array</title>
           <script language="javascript" type="text/javascript">
              var arr = new Array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi",
           "Samedi","Dimanche");
              document.write('THE DAYS IN A WEEK: <BR>');
              for(var i in arr)
              {
                     document.write(arr[i] + '<br>');
              }
           </script>
    </head>
</html>
Summary
   Loop statements allow to execute the same block
    of code multiple times depending whether the
    specified condition is sastified or not.
   Array is a collection of values of the same type.
   Javascript support three types of loop:
       While loop
       For loop
       Do….while loop
   Jump statements: break, continue
                                 Building Dynamic Websites/Session 1/ 22 of 16
Summary…
   There are two types arrays:
       Single dimensional arrays
       Multiple dimensional arrays
   For….in loop is an extension of the for loop.




                                      Building Dynamic Websites/Session 1/ 23 of 16

More Related Content

What's hot (20)

PDF
Javascript essentials
Bedis ElAchèche
 
PPTX
Javascript 101
Shlomi Komemi
 
PDF
Javascript basics
shreesenthil
 
PDF
Intro to JavaScript
Jussi Pohjolainen
 
PPT
eXo SEA - JavaScript Introduction Training
Hoat Le
 
PPT
Javascript
Manav Prasad
 
PDF
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
PDF
Swift internals
Jung Kim
 
PPTX
Javascript Basics
msemenistyi
 
PDF
A Re-Introduction to JavaScript
Simon Willison
 
PPTX
Java script
Adrian Caetano
 
PDF
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
PDF
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
PDF
Java Script Best Practices
Enrique Juan de Dios
 
PPTX
Hardened JavaScript
KrisKowal2
 
PPTX
5 Tips for Better JavaScript
Todd Anglin
 
PDF
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
PDF
Anonymous functions in JavaScript
Mohammed Sazid Al Rashid
 
PDF
Introduction to web programming with JavaScript
T11 Sessions
 
PDF
Bottom Up
Brian Moschel
 
Javascript essentials
Bedis ElAchèche
 
Javascript 101
Shlomi Komemi
 
Javascript basics
shreesenthil
 
Intro to JavaScript
Jussi Pohjolainen
 
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Javascript
Manav Prasad
 
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
Swift internals
Jung Kim
 
Javascript Basics
msemenistyi
 
A Re-Introduction to JavaScript
Simon Willison
 
Java script
Adrian Caetano
 
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Java Script Best Practices
Enrique Juan de Dios
 
Hardened JavaScript
KrisKowal2
 
5 Tips for Better JavaScript
Todd Anglin
 
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Anonymous functions in JavaScript
Mohammed Sazid Al Rashid
 
Introduction to web programming with JavaScript
T11 Sessions
 
Bottom Up
Brian Moschel
 

Similar to 10. session 10 loops and arrays (20)

PPSX
Javascript variables and datatypes
Varun C M
 
PPT
JavaScript
Rowena LI
 
PDF
JavaScript Looping Statements
Janssen Harvey Insigne
 
PDF
05 JavaScript #burningkeyboards
Denis Ristic
 
PDF
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
AlexShon3
 
PPTX
Java Script Basic to Advanced For Beginner to Advanced Learner.pptx
sanjaydhumal26
 
RTF
Java scripts
Capgemini India
 
PPTX
Java script
bosybosy
 
PPTX
JavaScript lesson 1.pptx
MuqaddarNiazi1
 
PDF
Javascript
orestJump
 
PPT
Javascript sivasoft
ch samaram
 
PDF
Handout - Introduction to Programming
Cindy Royal
 
PPTX
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
PDF
Javascript basics
Fin Chen
 
PDF
Java script introducation & basics
H K
 
PPT
JavaScript Arrays
Reem Alattas
 
PPTX
4TH QUARTER LESSONS-CP(IF STATEMENT).pptx
CamilleJoyVeniegas
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PDF
Javascript part1
Raghu nath
 
Javascript variables and datatypes
Varun C M
 
JavaScript
Rowena LI
 
JavaScript Looping Statements
Janssen Harvey Insigne
 
05 JavaScript #burningkeyboards
Denis Ristic
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
AlexShon3
 
Java Script Basic to Advanced For Beginner to Advanced Learner.pptx
sanjaydhumal26
 
Java scripts
Capgemini India
 
Java script
bosybosy
 
JavaScript lesson 1.pptx
MuqaddarNiazi1
 
Javascript
orestJump
 
Javascript sivasoft
ch samaram
 
Handout - Introduction to Programming
Cindy Royal
 
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
Javascript basics
Fin Chen
 
Java script introducation & basics
H K
 
JavaScript Arrays
Reem Alattas
 
4TH QUARTER LESSONS-CP(IF STATEMENT).pptx
CamilleJoyVeniegas
 
JavaScript - An Introduction
Manvendra Singh
 
Javascript part1
Raghu nath
 
Ad

More from Phúc Đỗ (15)

PPTX
15. session 15 data binding
Phúc Đỗ
 
PPTX
14. session 14 dhtml filter
Phúc Đỗ
 
PPTX
13. session 13 introduction to dhtml
Phúc Đỗ
 
PPTX
12. session 12 java script objects
Phúc Đỗ
 
PPTX
11. session 11 functions and objects
Phúc Đỗ
 
PPTX
09. session 9 operators and statements
Phúc Đỗ
 
PPT
08. session 08 intoduction to javascript
Phúc Đỗ
 
PPT
07. session 07 adv css properties
Phúc Đỗ
 
PPTX
06. session 06 css color_andlayoutpropeties
Phúc Đỗ
 
PPTX
05. session 05 introducing css
Phúc Đỗ
 
PPTX
04. session 04 working withformsandframes
Phúc Đỗ
 
PPT
03. session 03 using lists and tables
Phúc Đỗ
 
PPT
02. session 02 working with html elements
Phúc Đỗ
 
PPTX
15. session 15 data binding
Phúc Đỗ
 
PPT
01. session 01 introduction to html
Phúc Đỗ
 
15. session 15 data binding
Phúc Đỗ
 
14. session 14 dhtml filter
Phúc Đỗ
 
13. session 13 introduction to dhtml
Phúc Đỗ
 
12. session 12 java script objects
Phúc Đỗ
 
11. session 11 functions and objects
Phúc Đỗ
 
09. session 9 operators and statements
Phúc Đỗ
 
08. session 08 intoduction to javascript
Phúc Đỗ
 
07. session 07 adv css properties
Phúc Đỗ
 
06. session 06 css color_andlayoutpropeties
Phúc Đỗ
 
05. session 05 introducing css
Phúc Đỗ
 
04. session 04 working withformsandframes
Phúc Đỗ
 
03. session 03 using lists and tables
Phúc Đỗ
 
02. session 02 working with html elements
Phúc Đỗ
 
15. session 15 data binding
Phúc Đỗ
 
01. session 01 introduction to html
Phúc Đỗ
 
Ad

Recently uploaded (20)

PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Biography of Daniel Podor.pdf
Daniel Podor
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 

10. session 10 loops and arrays

  • 1. LOOPS AND ARRAYS Session 10
  • 2. Objectives  Describe while loop.  Explain for loop.  Describe do-while loop.  Explain break and continue statements.  Describe the methods of Array object.
  • 3. What is a loop?  Loop is a section of code in a program which is executed repeatedly, until a specific condition is satisfied.  There are three type of loop structures: The while loop The do-while loop The for loop
  • 4. The while loop  The while loop executes a block of code as long as the given condition remains Conditio false true. n  Syntax: true while (condition) { Execute body Exit loop statement(s); of loop }
  • 5. The while loop: Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>while loop demo</title> <script language="javascript" type="text/javascript"> var n=20; var i=0; document.write("Display the odd number <br>"); while(i<=n) { if(i%2 == 0) document.write(i + "t"); i++; } </script> </head> <body> </body> </html>
  • 6. The do-while loop  The do-while loop is similar to the while loop, but the do-while loop do evaluates the condition at the end of the loop. So that, the do-while loop Execute body executes at least once. of loop  Syntax: do true Conditio n { statement(s); false }while(condition); Exit loop
  • 7. The do-while loop: Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>while loop demo</title> <script language="javascript" type="text/javascript"> var n=20; var i=0; document.write("Display the even number <br>"); do { if(i%2 == 0) document.write(i + "t"); i++; } while(i<=n); </script> </head> <body> </body> </html>
  • 8. The for loop  Syntax: for(initialization; condition; increment/decrement) { statement(s); }  The initialization is an assignment statement that sets the loop control variable, before entering the loop.  The condition is a relational expression, which determines, when the loop will exit.  The increment/decrement defines how the loop control variable changes, each time the loop is executed.
  • 9. The for loop: Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>for loop demo</title> <script language="javascript" type="text/javascript"> var n=20; var i=0; document.write("Display the even number <br>"); for(i=0; i<n; i++) { if(i%2 == 0) document.write(i + "t"); } </script> </head> <body> </body> </html>
  • 10. break statement  The break statement can be used in the switch- case and loop constructs. It is used to exit the loop without evaluating the specified condition. for(initialization; condition; increment/decrement) { …. if(condition) break; … } ...
  • 11. break statement: Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Using break statement</title> <script language="javascript" type="text/javascript"> var n = prompt("Enter the number n:"); var i=0; for(i=2; i<n; i++) { if(n % i == 0) { document.write(n + " is not a prime number."); break; } } if(i == n) document.write(n + " is prime number."); </script> </head> </html>
  • 12. continue statement  The continue statement is mostly used in the loop constructs. It is used to terminate the current execution of the loop and continue with the next repetition by returning the control to the beginning of the loop. for(initialization; condition; increment/decrement) { …. if(condition) continue; … } ...
  • 13. continue statement: Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>continue statement demo</title> <script language="javascript" type="text/javascript"> var n=20; var i=0; document.write("Display the even numbers <br>"); for(i=0; i<=n; i++) { if(i%2 == 1) continue; else document.write(i + "t"); } </script> </head> </html>
  • 14. Single-dimensional arrays  An array is a collection of values stored in adjacent memory locations. These array values are referenced using a common array name.  The values of array are the same data type. These values can be accessed by using the subscript or index numbers. The index determines the position of element in the array list.  In a single-dimensional array, the elements are stored in a single row in the located memory.  In JavaScript, the first element has the index number zero. Index Value
  • 15. Declaring arrays There are three ways to declaring an array:  Using the Array object: declare an array by using the new operator, and then initialize the individual array elements: var arr = new Array(3); arr[0] = “Single”; arr[1] = “Married”; arr[2] = “Divorced”;  Initialize the array variable at the time of declaration: var arr = new Array(„Single‟,‟Married‟,‟Divorced‟);  Creates an array without using Array object: var arr = {„Single‟,‟Married‟,‟Divorced‟};
  • 16. Single-dimensional arrays - Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Single-dimensional array</title> <script language="javascript" type="text/javascript"> var arr = new Array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi","Dimanche"); document.write("The days in a week <br>"); for(i=0; i<arr.length; i++) { document.write(arr[i] + '<BR>'); } </script> </head> </html>
  • 17. Multi-dimensional arrays  A multi-dimensional array stores a combination of values of a single type in two or more dimensions.  A two-dimensional array represents as rows and columns similar to a table.  JavaScript does not directly support two-dimensional array. You can create two-dimensional array by creating an array of arrays. You first declare an array and then create another array to each element of the main array. var emp= new Array(3); emp[0] = new Array(„John‟,‟300‟); emp[1] = new Array(„David‟,‟400‟); emp[2] = new Array(„Richard‟,‟500‟);
  • 18. Multi-dimensional arrays - Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Single-dimensional array</title> <script language="javascript" type="text/javascript"> var emp = new Array(3); emp[0] = new Array('Huynh Bay','1900'); emp[1] = new Array('Minh Thanh','900'); emp[2] = new Array('Tan Hung','800'); document.write('<table border=1> <tr> <th>Name</th> <th>Salary</th> </tr>'); for(var i=0; i<emp.length; i++) { document.write('<tr>'); for(var j=0; j<emp[i].length; j++) document.write('<td>' + emp[i][j] + '</td>'); document.write('</tr>'); } </script> </head> </html>
  • 19. Array methods  An array is a set of values grouped together an identified by a single name. In JavaScript, an Array allows you to create arrays. It provides the length property that is used to determine the number of elements in an array.  The various methods allow you to access and manipulate the array elements: - concat: combines one or more array variables. - join: joins all the array elements into a string. - pop: retrieves the last element of an array. - push: appends one or more elements to the end of an array. - sort: sorts the array elements in alphabetical order. - reverse: retrieves the elements from the last to the first index position. - toString: converts the array elements into string.
  • 20. Array methods - Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Using method in array</title> <script language="javascript" type="text/javascript"> var days = new Array('Monday','Tuesday','Wednesday'); document.write('Number of days: ' + days.length + '<br>'); document.write('The days: ' + days.join(', ') + '<br>'); document.write('The days after adding more: ' + days.push('Thursday','Friday','Saturday') + '<br>'); document.write('The days after sorting:' + days.sort() + '<br>'); document.write('The days after sorting in desceding order:' + days.reverse() + '<br>'); </script> </head> </html>
  • 21. for … in Loop  The for…in loop is an extension of for loop. It enables you to perform specific actions on the array objects. The loop reads every element in the specified array and executes a block of code once for each element in the array.  Example: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Using method in array</title> <script language="javascript" type="text/javascript"> var arr = new Array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi","Dimanche"); document.write('THE DAYS IN A WEEK: <BR>'); for(var i in arr) { document.write(arr[i] + '<br>'); } </script> </head> </html>
  • 22. Summary  Loop statements allow to execute the same block of code multiple times depending whether the specified condition is sastified or not.  Array is a collection of values of the same type.  Javascript support three types of loop:  While loop  For loop  Do….while loop  Jump statements: break, continue Building Dynamic Websites/Session 1/ 22 of 16
  • 23. Summary…  There are two types arrays:  Single dimensional arrays  Multiple dimensional arrays  For….in loop is an extension of the for loop. Building Dynamic Websites/Session 1/ 23 of 16