Page 236 - Web_Application_v2.0_C12_Fb
P. 236

Output:




















              Traversing Through an Array—Using the for loop
              The for loop can be used to iterate over an array and access each array element.

              Example 44: To demonstrate how to traverse an array

                  <!DOCTYPE HTML>
                  <HTML>
                  <HEAD>
                  <TITLE>Accessing Array Elements</TITLE>
                  </HEAD>
                  <body>
                  <H2>JavaScript Arrays</H2>
                  <P>Using for loop for traversing an array.</p>
                  <font color=blue>
                  <SCRIPT>
                  const fruits = ["pineapple", "pear", "jackfruit", "strawberry"];
                  for (i=0;i<fruits.length;i++)
                  document.write(fruits[i]+"<br>");
                  </SCRIPT>
                  </FONT>
                  </BODY>
                  </HTML>
              Output:


















              In the above example, the for loop uses the counter ‘i’ as index value to access each element.
              If we try accessing a non-existent array index, we get undefined

                234   Touchpad Web Applications (Ver. 2.0)-XII
   231   232   233   234   235   236   237   238   239   240   241