JavaScript - Arrays
Javascript variables are used to store a single data (at a given time). However, since it is often required to manipulate large amounts of data, this concept shows its limitations, as it is difficult to manage a large number of distinct variables.
To remedy this Javascript provides a data structure for storing data in a "common variable": the array
A Javascript array, is a variable that can contain multiple independent data indexed by a number, called index. The index of an array is thus used to access data stored therein.
When the array is composed only of variables, is called a mono-dimensional array . Here's a way to represent it:
Index 0 1 2 3 Data data 1 data 2 data 3 data 4
The first element in an array always has an index of 0.
In an array of n elements, the nth element has the n-1 index.
When a array contains other arrays is referred to as a multidimensional arrays. Here is a representation of a multidimensional array:
0 1 2 3 data 1
(variable) data 2 (array)
0 1 2 data 1 data 2 data 3 data 3
(variable) data 4 (tableau)
0 1 data 1 data 2
It is possible to make use of a custom index to identify and define each value, it is called an associative array. Javascript indeed allows the use of a string or a specific number to index the values of an array??. Here is a sample representation of an associative array:
Idex "Paul" "André" "Pierre" "Jean-François" Data 16 22 12 25
Javascript provides several ways to create a table:
var MyArray = ["data 1", "data 2", "data 3", "data 4"]; var MyArray = new Array("data 1", "data 2", "data 3", "data 4");
The array is initialized with the above value. It should be noted that n array must be declared before it is assigned values??.
The declaration of an array is as follows:
var MyArray = new Array();
Access to the elements of an array is done by writing the name of the array followed by brackets containing the index of the element.
var MyArray = ["Teebo", "Eaulive", "Asevere", "Kalamit", "Serge", "Chat_Teigne", "BmV"]; documenrite("The 4th element of the array is "+MyArray[3]); // Display "The 4th element of the array is Kalamit"
To create an associative array, you have to declare an array variable, then write the name of the array, followed by a name (index) between brackets and assign the data usng assignment operator:
MyArray[0] = "Bonjour"; MyArray["Pierre"] = 12; MyArray["Jean-François"] = 25;
Javascript offers the Array object with many methods for manipulating arrays: Javascript - The Array object
Original document published on CommentcaMarcheet.