Arrays · Tableaux
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.
Les tableaux contiennent des listes
- Un tableau est une liste ordonnée de valeurs dans
[ ... ]. - Accédez à un élément par son index, en comptant à partir de
0:arr[0]est le premier. .lengthvous dit combien d'éléments il y a.
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.
Ajouter et supprimer des éléments
.push(x)ajoutexà la fin ;.pop()supprime l'dernier élément.- Le tableau grandit et rétrécit au fur et à mesure.
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 · Index, push et pop
Items are numbered from 0. push adds to the end; pop removes from the end. · Les éléments sont numérotés à partir de 0. push ajoute à la fin ; pop retire de la fin.
Loop over an array
- A
forloop with an index visits each item, from0tolength - 1.
Parcourir un tableau
- Une boucle
foravec un index visite chaque élément, de0àlength - 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.
Erreurs courantes
- Indexez à partir de
0;a.lengthest la taille. pushajoute à la fin ;popretire de la fin.
Now you try
- Use an index, or a loop, on each array.
- Press Check answer to test it.
À vous maintenant
- Utilisez un index, ou une boucle, sur chaque tableau.
- Appuyez sur Vérifier la réponse pour tester.
let colours = ["red", "green", "blue"]. Log the second item, colours[1] (it is green). · let colours = ["red", "green", "blue"]. Loguez le deuxième élément, colours[1] (il est green).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
let nums = [4, 8, 15, 16]. Log how many items it has with .length (it is 4). · let nums = [4, 8, 15, 16]. Loguez combien d'éléments il y a avec .length (il est 4).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
let stack = [1, 2]. Use .push to add 3, then log the array (it is [1,2,3]). · let stack = [1, 2]. Utilisez .push pour ajouter 3, puis loguez le tableau (il est [1,2,3]).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Use a for loop to add up every number in nums and log the total (it is 43). · Utilisez une boucle for pour additionner tous les nombres de nums et loguez le total (il est 43).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.