The programming language JavaScript tiene la posibilidad de definir una matriz de variables en un objeto llamado Array. En JavaScript, una matriz también works as a list, a stack, or a queue.
A menudo nos encontramos con que necesitamos una colección ordenada , donde tenemos un primer, un segundo, un tercer elemento y así sucesivamente. Por ejemplo, necesitamos eso para almacenar una lista de algo: usuarios, productos, elementos HTML, etc. Y es por eso que el día de hoy empezaremos a manejar los Arrays en JS.
How to declare an Array?
There are two basic syntax for declaring an empty array.
let arr = new Array (); let arr = [];
The 90% of the cases uses the second syntax, since we can supply initial elements in parentheses. For example:
let arr colors ["yellow", "blue", "red", "white"];
The elements in an array have their own enumeration or sub-index, with which we can access an element of the array.
Note: The first element will always start with sub-index 0, and not sub-index 1, in fact; the sub-index 1 would correspond to the second element of the array.
let colors ["yellow", "blue", "red", "white"]; alert (colors [0]); // yellow alert (colors [1]); // blue alert (colors [2]); // red alert (colors [3]); // White
We can also substitute elements of the array.
colors [3] = "green"; // now the array will be: ["yellow", "blue", "red", "green"];
Or even, you can add more elements to the array.
colors [4] = "light blue"; // now the array is composed of: ["yellow", "blue", "red", "green", "light blue"]
We can find out how many elements are in an array using length.
let colors = ["yellow", "blue", "red"]; alert (colors.length); //3
We can also use alert to show all the arrays.
let colors = ["yellow", "blue", "red"]; alert (colors); //yellow blue red
Elements of any type can be stored in an array.
// mixing the values let arr = ['yellow', {name: 'Juan'}, true, function () {alert ('hello'); }]; // we get the object at index 1 and then display its name alert (arr [1] .name); // John [php] // get the function at index 3 and execute it arr [3] (); // Hello
Pop / push, shift / unshift methods
A line it is one of the most common uses of a matrix. In computing, this means an ordered collection of items that supports two operations:
- Push: append an element to the end.
- Shift: you get an item from the beginning, moving up the queue so that the second item becomes the first.
Arrays support both operations.
In practice we find it very often. For example, a queue of messages to be displayed on the screen.
There is another use case for arrays: the data structure called a stack.
Supports two operations:
- Push: add an element at the end.
- Pop: take an element from the end.
So new elements are always added or taken from the "final".
A pile is usually illustrated as a pack of cards - new cards are added to the top or taken from the top:
For stacks, the last item pushed is received first, it is also called the principle of LIFO (last in, first out). For the queues, we have FIFO (First in, first out).
Arrays in JavaScript can function both as a queue and as a stack. They allow adding / removing elements from both the beginning and the end.
In computing, the data structure that allows it is called deque.
- Methods used at the end of an array or matrix
Pop: extracts the last element from the array and returns it.
let colors = ["Yellow", "Orange", "Green"]; alert (colors.pop ()); // remove "Green" and alert it alert (colors); // Yellow orange
Push: Add an element to the end of an array.
let colors = ["Yellow", "Orange"]; colors.push ("Green"); alert (colors); // Yellow, Orange, Green
- Methods that are used at the beginning of the matrix
Shift: extracts the first element of the array and returns it.
let fruits = ["Pear", "Orange", "Strawberry"]; alert (fruits.shift ()); // Remove Pear and alert it alert (fruits); // Orange, Strawberry
Unshift: add an element to the beginning of the array:
let fruits = ["Coconut", "Strawberry"]; fruits.unshift ('Orange'); alert (fruits); // Orange, Coconut, Strawberry
Methods push and unshift they can add multiple items at once:
let fruits = ["Orange"]; fruits.push ("Strawberry", "Coconut"); fruits.unshift ("Pineapple", "Lemon"); // ["Pineapple", "Lemon", "Orange", "Strawberry", "Coconut"] alert (fruits);
Internally manipulating the matrix
An array is a special type of object. The square brackets used to access a property arr [0] they actually come from the syntax of the object. The numbers are used as keys.
They extend objects that provide special methods for working with ordered collections of data and also with the property length. But at the core it is still an object.
Remember, there are only 7 basic types in JavaScript. The array is an object and therefore behaves like an object.
For example, it is copied by reference:
let fruits = ["Banana"] let arr = fruits; // copy by reference (two variables refer to the same array) alert (arr === fruits); // true arr.push ("Pear"); // modify the array by reference alert (fruits); // Banana, Pear - are 2 items now
But what makes the arrangements really special is their internal rendering. The engine tries to store its elements in the contiguous memory area, one after the other, and there are also other optimizations to make the arrays work really fast.
But they all break if we stop working with an array as an "ordered collection" and start working with it as if it were a normal object.
For example, we can technically do this:
let fruits = []; // form an array fruits [99999] = 5; // assign a property with an index much higher than its length fruits.age = 25; // create a property with an arbitrary name
That is possible, because arrays are objects at their base. We can add any property to them.
But the engine will see that we are working with the matrix as with a normal object. Matrix specific optimizations are not suitable for such cases and will be disabled, their benefits will disappear.
The ways to misuse an array:
- Add a non-numeric property like arr.test = 5.
- Make holes, like: add arr [0] and then arr [1000] (and nothing in between).
- Fill the array in reverse order, such as arr [1000], arr [999], and so on.
Note: Please think of arrays as special structures for working with ordered data. They provide special methods for that. Arrays are carefully tuned within JavaScript engines to work with contiguous ordered data, use it this way. And if you need arbitrary keys, it is very likely that you really need a normal object.