Arrays · Arreglos
Arrays hold lists
- An array is an ordered list of values in
[ ... ]. - Reach an item by its index, counting from
0:arr[0]is the first. .lengthtells you how many items there are.
Los arrays almacenan listas
- Un array es una lista ordenada de valores en
[ ... ]. - Accede a un elemento por su índice, contando desde
0:arr[0]es el primero. .lengthte indica cuántos elementos hay.
let nums = [10, 20, 30];
console.log(nums[0]); // → 10
console.log(nums.length); // → 3
Add and remove items
.push(x)addsxto the end;.pop()removes the last item.- The array grows and shrinks as you go.
Agregar y eliminar elementos
.push(x)agregaxal final;.pop()elimina el último elemento.- El array crece y se encoge según avanzas.
let nums = [10, 20, 30];
nums.push(40);
console.log(nums); // → [10,20,30,40]
nums.pop();
console.log(nums); // → [10,20,30]
Index, push and pop · Índice, push y pop
Items are numbered from 0. push adds to the end; pop removes from the end. · Los elementos se numeran desde 0. push añade al final; pop elimina del final.
Loop over an array
- A
forloop with an index visits each item, from0tolength - 1.
Recorrer un array
- Un bucle
forcon un índice visita cada elemento, desde0hastalength - 1.
let nums = [1, 2, 3];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]); // → 1, then 2, then 3
}
Common mistakes
- Index from
0;a.lengthis the size. pushadds to the end;popremoves from the end.
Errores comunes
- Cuenta los índices desde
0;a.lengthes el tamaño. pushagrega al final;popelimina del final.
Now you try
- Use an index, or a loop, on each array.
- Press Check answer to test it.
Ahora tú lo intentas
- Usa un índice o un bucle para cada array.
- Presiona Comprobar respuesta para ponerlo a prueba.
let colours = ["red", "green", "blue"]. Log the second item, colours[1] (it is green). · let colours = ["red", "green", "blue"]. Registre el elemento segundo, colours[1] (es green).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
let nums = [4, 8, 15, 16]. Log how many items it has with .length (it is 4). · let nums = [4, 8, 15, 16]. Registre cuántos elementos tiene con .length (es 4).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
let stack = [1, 2]. Use .push to add 3, then log the array (it is [1,2,3]). · let stack = [1, 2]. Use .push para añadir 3, luego registre el arreglo (es [1,2,3]).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use a for loop to add up every number in nums and log the total (it is 43). · Use un bucle for para sumar todos los números en nums y registre el total (es 43).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.