Javascript Array Objects:

Javascript Objects

Array-object

An array is a variable that can store many variables. An array is an ordered set of values that you refer to with a name and an index.

 

  • The array is a special type of variable.
  • Values are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets.
    Example:
    myArray[2] = “apple”;
  • Values in an array are accessed with the array name and location of the value.
    Example:
    myArray[2];
  • Javascript has built in functions for arrays, so check out these built in array functions before writing code yourself!

 

How to create an Array object:
There are 2 ways :

<1> arrayName = new Array([LengthofArray])
or

<2> arrayName = new Array([firstelement, secondelement, …, lastelement])

Eg: You can declare a new array for storing employee names in a company through EmployeeArray= new Array().
You can assign values to this array as:

EmployeeArray[0]=”Lisa”;

EmployeeArray[1]= “Bob”;

EmployeeArray[2]= “Frank”;

or in a single line:

var EmployeeArray=Array(“Lisa”,Bob”,”Frank”)

JavaScript 1.0 (Netscape Navigator 2.x and Microsoft Internet Explorer 3.x) does not support Array-object. In such cases, use the following code:

function EmployeeArray() {
  this.length = EmployeeArray.arguments.length

  for (var i = 0; i < this.length; i++)

    this[i+1] = EmployeeArray.arguments[i]

}

You can now create an array with:
Employees= new EmployeeArray(“Lisa”,”Bob”,”Frank”);

Javascript Array Sorting

Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written and can be accessed by using the Array’ssort method.

Javascript Code:

 
<script type="text/javascript"> <!-- var myArray = new Array(); myArray[0] 
= "Orange"; myArray[1] = "Apple"; myArray[2] = "Grapes"; myArray.sort(); 
document.write(myArray[0] + myArray[1] + myArray[2]); //--> </script> 

Display:

AppleGrapesOrange

Leave a Comment