Page 82 - DCAP202_Fundamentals of Web Programming
P. 82

Unit 6: Introduction to JavaScript




          However, what if you want to loop through the cars and find a specific one? And what if you had  Notes
          not 3 cars, but 300?
          The best solution here is to use an array!





             Notes  An array can hold all your variable values under a single name. And you can access
             the values by referring to the array name.
          Each element in the array has its own ID so that it can be easily accessed.

          6.9.1 Creating Arrays

          An array can be defined in three ways.

          The following code creates an Array object called myCars:
          1:
          var  myCars=new  Array();  //  regular  array  (add  an  optional  integer
          myCars[0]=”Mercedes”;  //  argument  to  control  array’s  size)
          m   y   C    a   r   s   [   1    ]   =   ”   F   e    r   a   r   i   ”   ;
          myCars[2]=”BMW”;
          2:
          var  myCars=new  Array(“Mercedes”,”  Ferari  “,”BMW”);  //  condensed  array
          3:
          var  myCars=[“  Mercedes  “,”  Ferari  “,”BMW”];  //  literal  array

               !
             Caution  If you specify numbers or true/false values inside the array then the variable type
             will be Number or Boolean, instead of String.

          6.9.2 Access an Array

          You can refer to a particular element in an array by referring to the name of the array and the
          index number. The index number starts at 0.

          The following code line:
          document.write(myCars[0]);
          Will  result  in  the  following  output:
          Mercedes
          6.9.3 Modify Values in an Array

          To modify a value in an existing array, just add a new value to the array with a specified Index
          number:
          myCars[0]=”Opel”;
          Now,  the  following  code  line:
          document.write(myCars[0]);
          will result in the following output:
          Opel





                                           LOVELY PROFESSIONAL UNIVERSITY                                   75
   77   78   79   80   81   82   83   84   85   86   87