Accueil > JavaScript > JavaScript – Arrays

JavaScript – Arrays

  1. Properties
    1. length
  2. Methods
    1. concat()
    2. join()
    3. reverse()
    4. slice()
    5. sort()
  3. Multidimensional arrays
  4. Associative arrays

Arrays allow to easily stock data in order to access to it after. A variable can only contain a unique value. An array can contain almost an infinite number. Because JavaScript is object oriented, arrays don’t make an exception : they are objects too with properties and methods.

To create an object, the syntax is the following:

var name = new constructor(argument1, argument2, ...);

The name must be a valid one, which must follow the same rules as for the variable names. The constructor must be a valid constructor function (we will study this in details in the following posts). In our case, the constructor is Array (with a uppercase A). Then, there is some arguments. They are optional.

Therefore, to create an array which we will name books, we write:

var books = new Array();// don't forget the empty parenthesis

Then, it is possible to access to the array’s elements by specifying the element index between brackets ([ and ]). Thus:

var books = new Array();

books[0] = "Critias";
books[1] = "Thoughts";
books[2] = "Odysseys";

document.write("1<sup>st</sup> book : " + books[0] + "<br>");// Critias
document.write("2<sup>nd</sup> book : " + books[1] + "<br>");// Thoughts
document.write("3<sup>thd</sup> book : " + books[2] + "<br>");// Odysseys

A second possibility to create an array is to use the literal way. Elements have to be given as arguments during the array creation. The following example is the equivalent of the previous:

var books = new Array("Critias", "Thoughts", "Odysseys");
document.write("1<sup>st</sup> book : " + books[0] + "<br>");// Critias
document.write("2<sup>nd</sup> book : " + books[1] + "<br>");// Thoughts
document.write("3<sup>thd</sup> book : " + books[2] + "<br>");// Odysseys

It is also possible to use an other form, without using the Array keyword, but with brackets:

var books = ["Critias", "Thoughts", "Odysseys"];
document.write("1<sup>st</sup> book : " + books[0] + "<br>");// Critias
document.write("2<sup>nd</sup> book : " + books[1] + "<br>");// Thoughts
document.write("3<sup>thd</sup> book : " + books[2] + "<br>");// Odysseys

A last possibility is to give as an argument the length of this one. Example:

var myArray = new Array(10);// 10 elements

// see below for the length property
document.write(myArray.length);// Output -> 10

Properties

Like any other object, Array has also properties. Actually, Array has got only one property:

length
Return the number of elements an array contains. For instance:

var books = new Array("Critias", "Thoughts", "Odysseys");

document.write(books.length);// output -> 3

This property is very useful to scan an array with a loop:

var books = new Array("Critias", "Thoughts", "Odysseys");

for(var i=0; i < books.length; i++)
document.write("books N°" + i + " : " + books[i] + "<br>");

Méthodes

concat()
Allows to make one array from two different ones. The array to add has to be passed as an argument:

var myBooks = new Array("Critias", "Thoughts", "Odysseys");
var yourBooks = new Array("Journey in Italia", "Logic of Scientific Discovery");

myBooks.concat(yourBooks);// we add the yourBooks array
join()
Makes a string from the array’s elements. Elements are separated with the string given as an argument, but which is optional.
Example:

var books = new Array("Critias", "Thoughts", "Odysseys");
var Text = books.join("<br>");

document.write(Text);
reverse()
Reverses the order of array’s elements. 1st becomes the last, 2nd the penultimate and so on…

var books = new Array("Critias", "Thoughts", "Odysseys");
books.reverse();

for(var i=0; i < books.length; i++)
document.write(books[i] + "<br>");
slice()
Returns an array which contains a part of the array. 1st argument is related to the start index. 2nd argument is optional. It matches to the end index. If it’s omitted, all indexes until the end of the array will be returned.

var list = new Array("one", "two", "three", "four", "five");
var mylist = list.slice(1, 4);

for(var i=0; i < mylist.length; i++)
document.write(mylist[i] + "<br>");
sort()
Allows to sort an array in accordance with its elements. If no arguments are given, the array is sorted following an alphabetical order. The allowed argument is a sort function (functions will be explained later). This function must accept two arguments and must return a negative value is the first argument must be moved before the second one, or a positive value if it is the contrary.

var list = new Array("one", "two", "three", "four", "five");
list.sort();

for(var i=0; i < list.length; i++)
document.write(list[i] + "<br>");

Multidimensional arrays

To create an array with more than one dimension, there is nothing more to do than create an  Array object array for each row of the array:

var table = new Array(10);

for(var i=0; i < table.length; i++)
table[i]=new Array(10);

// One access to the array's elements like that:
table[5][5] = "I'm almost in the middle of the table";

Based on this idea, it is possible to use as many dimensions as we want.

Associative arrays

The difference between an associative array and a classical array is that an associative array don’t use the numerical way to index the elements, but names. For instance, with a classical array, one access to an element like that:

var myArray = new Array();

myArray[0] = "Goldorak";// access to the element 0

document.write(myArray[0]);// output -> Goldorak

With an associative array, we access like that:

var myArray = new Array();

myArray["name"] = "Goldorak";// we access to the element "name"

document.write(myArray["name"]);// output -> Goldorak

These arrays are in some cases more handy to use. To scan an array of this kind, it is required to use the  for...in loop:

var winners = new Array();

// Critérium du Dauphiné 4-11 juin 2000
winners["Grenoble- La Bastille (prologue)"] = "Alberto Lopez de Munain";
winners["Grenoble - Lyon"] = "Frédéric Guesdon";
winners["Châtillon sur Chalaronne - Saint Etienne"] = "Fabrice Gougot";
winners["Saint Etienne - Saint Etienne (contre la montre)"] = "Lance Armstrong";
winners["Romans - Le mont Ventoux"] = "Tyler Hamilton";
winners["Beaumes de Venise - Dignes les Bains"] = "Tyler Hamilton";
winners["Digne les Bains - Briançon"] = "Inigo Cuesta";
winners["Saint Jean de Maurienne - Salanches"] = "Laurent Jalabet";

for(stage in winners)
document.write(stage + " : " + winners[stage] + "<br>");
Categories: JavaScript Tags:
  1. Pas encore de commentaire
  1. Pas encore de trackbacks