·  JavaScript – Syntax – Collections – Array

 

- Info:

  - This tutorial shows how to use arrays in Java Script.

  - This tutorial is based on http://www.w3schools.com/js/js_obj_array.asp.

 

- Additional Tutorials:

  - JavaScript – Syntax – Collections – Array 2D

 

- Array Create:

  - Regular array:

  array    = new Array();                   //Create empty array.

  array    = new Array(100);                //Create array with 100 empty elements.

  array[0] = "one";                         //Add element at index 0.

  array[1] = 2;                             //Add element at index 1.

  - Condesed array:

    array    = new Array("one",2,"three",4,5);//Create array with initial 5 elements.

  - Literal array:

    array    = [];                            //Create empty array.

    array    = ["one",2];                     //Create array with initial 5 elements.

    array    = [,"second",,,4,,];             //Create array with initial 7 elements.

 

- Array – Methods and Properties

  array    = [10, 20, 30, 40, 50];

  count    = array.length;               //5  Number of elements in array.

  element  = array.pop();                //50 Removes and returns last  element from an array.

  element  = array.shift();              //10 Removes and returns first element from an array.

  count    = array.unshift(1);           //6  Adds element  to the front of array and returns new length.

  count    = array.unshift(1,2,3);       //8  Adds elements to the front of array and returns new length.

  count    = array.push(60);             //6  Adds element  to the end   of array and returns new length.

  newArray = array.concat([100,200]);    //   Joins two arrays and returns a new array.

  string   = array.join();               //"10, 20, 30, 40, 50" Joins all elements of array into string.

             array.sort();               //   Sorts the elements of array alphabeticly.

             array.reverse();            //   Sorts the elements of array alphabeticly in reverse order.

  subArray = array.slice(1,2);           //20,30 Return array section from start to end index.

  subArray = array.slice(3);             //40,50 Return array section from start till end.

  subArray = array.slice(-3,-1);         //30,40 Use negative numbers to select index from end.

  subArray = array.slice(-2);            //40,50 Use negative numbers to select index from end.

             array.splice(1,2);          //10,40,50 Remove 2 elements from index 1.

             array.splice(1,0,"E1","E2");//10,E1,E2,20,30,40,50 Add elements at index 1.

             array.splice(1,2,"E1","E2");//10,E1,E2,40,50 Fom index 1 remove 2 elements and add new ones.

 

- Array – Display:

  array    = [10, 20, 30, 40, 50];

  window.alert(array); //10,20,30,40,50

  console.log (array); //10,20,30,40,50

 

- Element – Reference:

  array[0] = "one";