Using Javascript arrays

How to use Javascript arrays.

  • All arrays are objects and inherited by the Array object, which is a build-in object in Javascript.
  • An array object can contain a collection of datavalues​​, where each datavalue has an index number as reference.
  • JavaScript is an untyped language that cause an array object to contain different datatypes. This means that an array can contain other arrays, objects, functions (functions are datavalues ​​in Javascript), dates, primitive values ​​and so on.
  • The index is a positive number starting with 0 as the first location for a datavalue. This means that the third datavalue has the index of 2.
  • For either to retrieve a datavalue, or insert a datavalue in an array, we can use square brackets, that encloses the index, after the name of the array.

Creating Javascript arrays.

  • The easiest way to create an array is to use the literal notation, which include use of the square brackets:

    Example:
    <script type="text/javascript">
      var person1 =["George","Collins"];
      var person2 =["Ricard","Marvin"];
      var peoples=["Google",person1,person2];
      document.write("Last name of person1: "+person1[1]+"<br>");
      document.write("Last name of person2: "+peoples[2][1]+"<br>");
     </script>
  • In Javascript, new array objects can be created using the Array object.
  • The Array object is a constuctor function type, so we need to use the keyword, new to create a new array object.
  • You can also use the Array object as a function, which will return an array object as well.
  • This means we can create an array object in three ways:
    var myarray1=[]; // is an ease way to create an empty array
    var myarray2= new Array(); // using constructor (Array) to create an array
    var myarray3= Array(); // using Array as a function to create an array
  • An array that you define contains a property, length, indicate the number of items contained in the array. This means that an empty array has a length equal to 0.
  • Although an array has a length equal to 0, you can add new items using square brackets with an index that is greater than or equal to the existing array length.

    Example:
    <script type="text/javascript">
      var myarray =[];
      document.write("The array length: "+myarray.length+"<br>");
      myarray[3]="Hallo";
      document.write("The fourth location contains: "+myarray[3]+"<br>");
      document.write("The array length: "+myarray.length+"<br>");
      document.write("The first location contains: "+myarray[0]+"<br>");
      myarray[3]=undefined;
      delete(myarray[3]);
      document.write("The fourth location contains: "+myarray[3]+"<br>");
      document.write("The array length: "+myarray.length+"<br>");
      document.write("The first location contains: "+myarray[0]+"<br>");
     </script>
  • Locations in an array that has no datavalue is considered as undefined.
  • You can remove the datavalue in an array location by setting it to undefined or using a delete statement as shown in the example above. In both cases you will still retain the same array length.
  • You can remove all datavalues ​​in the array object by setting the length property to 0.

Most used array methods.

  • Using push and pop methods on an array.

    Array object has a method, push(), which adds a new location to the array. The new location becomes the last item in the array and the length of the array will increase by one.

    If you want to remove the last item in an array you must use the Array object pop() method. This will result in that the length of the array is reduced by one.


    Example:
    <script type="text/javascript">
      var myarray =[];
      document.write("The array length: "+myarray.length+"<br>");
      myarray.push("Hallo");
      myarray.push(function(){alert("I am a function"); return "OK";});
      document.write("The array length: "+myarray.length+"<br>");
      document.write("The first location contains: "+myarray[0]+"<br>");
      document.write("Execute second location with return: "+myarray[1]()+"<br>");
      document.write("Remove the second location which contains: "
                                     +myarray.pop()+"<br>");
      document.write("The array length: "+myarray.length+"<br>");
      document.write("Removes the remaining location that contains: "
                                     +myarray.pop()+"<br>");
      document.write("The array length: "+myarray.length+"<br>");
     </script>
  • To sort datavalues in an array.

    The Array object has a sort() method to sort the datavalues in the array. This method has an optional parameter.

    If the parameter is specified, it must be a function (compare function) with two parameters. The compare function shall return either a value >0, 0, or <0. Comparison function should always return 0 for equality of the two parameter values​​.

    For an ascending sort; compare function must return a positive value if the first parameter value is considered to be greater than the second parameter value and a negative value for the opposite.

    For an descending sort; compare function must return a negative value if the first parameter value is considered to be greater than the second parameter value and a positve value for the opposite.

    If the parameter of the sort() method is not specified the method will sort the array as if there are strings to be sorted. Data values ​​in the array locations that are not strings will be temporarily converted to strings before sorting is performed in this case.


    Example:
    <script type="text/javascript">
    var arr = [4343, 44, 1331, 56];
    arr.sort();   // Alphabetical order:  1331,4343,44,56
    document.write(arr+"<br>");
    // Numerical ascending order sort: 44,56,1331,4343
    arr.sort(function(p1,p2) {
               return p1-p2;
           });
    document.write(arr+"<br>");
    // Numerical descending order sort: 4343,1331,56,44
    arr.sort(function(p1,p2) {
               return p2-p1;
           });
    document.write(arr+"<br>");
    </script>
  • Convert datavalues of an array to a string.

    The Array object has a join() method to convert the datavalues in an array to a string.

    The method has an optional parameter to specify a string that will be inserted between the locations in the resulting string. If you not specifies such a string, a comma will be used.


    Example:
    <script type="text/javascript">
    var arr = ["Boolean","Math","Number","Object","String"];
    // without a parameter streng - comma will be used
    document.write(arr.join()+"<br>");
    // with a parameter streng 
    document.write("<ul><li>"+arr.join("</li><li>")+"</li></ul>");
    </script>
  • Reverses the order of the datavalues in an array.

    The Array object has a reverse() method that reverses the order of the datavalues in an array and returns the result.

    Example:
    <script type="text/javascript">
    var arr = ["Boolean","Math","Number","Object","String"];
    // reverse the order of datavalues in the array
    var rev=arr.reverse();
    // The processed array
    document.write(arr+"<br>");
    // The returned array is the same as the processed array
    document.write(rev+"<br>");
    </script>

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.