Este objeto nos permitirá construir arrays; Los arrays pueden contener cualquier tipo básico, y su longitud cambiará dinámicamente cuando añadamos un artículo (así que no tenemos que preocuparnos de eso). Para tener un objeto Array, debemos crearlo con su constructor, por ejemplo, si escribimos:
a=new Array(15);
Vamos a crear una variable a, que contiene 15 elementos, numerados entre 0 y 14. Para llegar a cada ítem individual, usaremos una [i] notación; Cambiará de 0 a N-1, y es el número de elementos que pasamos al constructor N.
También podemos inicializar la declaración array, con los valores que queremos ir directamente al constructor, por ejemplo:
a=new Array(21,"cadena",true);
Como se muestra, los elementos de la matriz no tienen que ser del mismo tipo.
Así que si ponemos un argumento en la llamada al constructor, éste será el número de elementos de la matriz (y luego los valores se les asignarán), y si ponemos más de uno, los argumentos que construyen arrays podrán comenzar con tantos elementos.
Como una mención especial de esto, podríamos hacer esto. Las iniciales que vemos son:
a=new Array("cadena");
a=new Array(false);
Inicializar arl array, en el primer caso, con un elemento que tiene una cadena de cadena y, en el segundo caso, un elemento con un contenido falso.
El hecho de que hayamos escrito sobre la inicialización de matrices con diferentes valores significa que escribimos esto:
a=new Array(2,3);
No tendremos una matriz de 2 filas y 3 columnas, sino más bien una matriz que contiene el primer elemento 2 y el segundo elemento 3. Entonces, ¿cómo creamos una matriz bidimensional? (matriz bidimensional es bastante común en la construcción). Vamos a crear una matriz con las filas deseadas, y luego cada elemento de la matriz comenzará con la matriz que queremos con las columnas que queremos. Por ejemplo, si desea crear filas de 4 filas y 7 columnas, escribiremos:
a=new Array(4);
for(i=0;i<4;i++) a[i]=new Array(7);
y (i,j) posición relativa en el array, a[i][j];
sort(). Organizar los elementos de la matriz de acuerdo con la orden lexicográfica
Ejemplos
Tres formas diferentes:
1: Irregular:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2: Corta:
var myCars=new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];
Usted se refiere a un elemento de matriz al referirse a la número de índice .
Esta declaración accede al valor del primer elemento de coches:
var name = cars[0];
Esta declaración modifica el primer elemento de coches:
cars[0] = "Opel"
Ejemplo:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
La verdadera fuerza de matrices de JavaScript son la incorporada en las propiedades y métodos de la matriz:
var x=myCars.length // myCars-eko elementu kopurua
var y=myCars.indexOf("Volvo") // "Volvo" elemtuaren index balioa
In this tutorial we will use a script to display arrays inside a <p> element with id="demo":
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
The first line (in the script) creates an array named cars.
The second line "finds" the element with id="demo", and "displays" the array in the "innerHTML" of it.
In JavaScript, all objects have the valueOf() and toString() methods.
The valueOf() method is the default behavior for an array. It returns an array as a string:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.valueOf();
For JavaScript arrays, valueOf() and toString() are equal.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
The join() method also joins all array elements into a string.
It behaves just like toString(), but you can specify the separator:
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is: Popping items out of an array, or pushing items into an array.
The pop() method removes the last element from an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
The push() method adds a new element to an array (at the end):
Remember: [0] is the first element in an array. [1] is the second. Array indexes start with 0.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
The pop() method returns the string that was "popped out".
The push() method returns the new array length.
Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first element of an array, and "shifts" all other elements one place down.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
The shift() method returns the string that was "shifted out".
The unshift() method returns the new array length.
Array elements are accessed using their index number:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi"
The length property provides an easy way to append a new element to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
Using delete on array elements leaves undefined holes in the array. Use pop() or splice() instead.
The splice() method can be used to add new items to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0,1); // Removes the first element of fruits
The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
The sort() method sorts an array alphabetically:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Use the same trick to sort an array descending:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments:
function(a, b){return a-b}
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
Example:
When comparing 40 and 100, the sort() method calls the compare function(40,100).
The function calculates 40-100, and returns -60 (a negative value).
The sort function will sort 40 as a value lower than 100.
How to find the highest value in an array?
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
// now points[0] contains the highest value
And the lowest:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
// now points[0] contains the lowest value
The concat() method creates a new array by concatenating two arrays:
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
The concat() method can take any number of array arguments:
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
The slice() method slices out a piece of an array:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
For a complete reference, go to our Complete JavaScript Array Reference.
The reference contains descriptions and examples of all Array properties and methods.