Page 201 - Web Applications (803) Class 12
P. 201

document.write(i*i+", ");
                    }</script>
                    </font>

                    </body> </html>
                 Output of the preceding program is as follows:













                   3.9 ARRAYS IN JAVASCRIPT

                 An array is a special variable, with the capacity to hold several values. Syntax:

                    const array_name = [element1, element2, ...];
                 It is a common practice to declare arrays with the const keyword.

                 Creating Arrays

                 1.  The simplest way of creating an array is using the array literal:
                    const animals = ["lion", "tiger", "giraffe", "elephant"];
                 2.  You can also create a blank array, and then specify the elements:

                    const birds = [];
                    birds[0]= "pigeon";
                    birds[1]= "sparrow";
                    cars[2]= "eagle";
                 3.  Using the keyword new:
                    const currency = new Array("Dollar", "Yen", "Pound");

                 Accessing Array Elements
                 Array elements can be accessed using the respective index value.

                                                      lion        tiger       giraffe     elephant

                                     Index value       0            1            2            3

                 Let us understand through an example:

                    <html>
                    <body text="red">
                    <h2>Accessing array elements</h2>
                    <font color=blue>

                    <script>
                    const cars = ["Ferrari", "WagonR", "BMW"];
                    document.write("Element 2 is " + cars[1]);
                    //element values can be changed


                                                                                          Web Scripting—JavaScript   199
   196   197   198   199   200   201   202   203   204   205   206