Arrays
An array keeps values in order. Read them by index from 0, add with push, count with length and walk through them with for...of.
Indexes start at 0
An array is a list of values in order, inside square brackets. Each one sits at a numbered position called an index, and counting starts at 0.
const queue = ["Ana", "Ben", "Cleo"];
queue[0] // "Ana"
queue[2] // "Cleo"
queue.length // 3
queue[queue.length - 1] // "Cleo", the last one
queue[3] // undefined: nothing thereThe last index is always length - 1. Asking past the end does not crash, it just gives undefined.
Adding and looping
push adds to the end and changes the array, even one made with const (the name still points at the same array; only its contents change).
queue.push("Dev");To do something with every item, for...of hands you each value in turn:
for (const name of queue) {
console.log(name + " is in the lobby");
}Need the position too? Use a counting loop: for (let i = 0; i < queue.length; i++). Note <, not <=.
Run it: a playlist
Run it, then change one thing and run it again.
const playlist = ["Neon Rain", "Late Bus", "Stone Road"];
playlist.push("Paper Planes");
console.log("Songs:", playlist.length);
console.log("First:", playlist[0]);
console.log("Last:", playlist[playlist.length - 1]);
for (let i = 0; i < playlist.length; i++) {
console.log(i + 1 + ". " + playlist[i]);
}
Add the last round
kills holds a player's kills in each round. A late round just finished with 7 kills: add it to the end of the array. Then print how many rounds there were and the total kills, exactly like this:
Rounds: 5
Total: 30Use a loop for the total, not a number you worked out yourself.
Constraint
- Add up the kills with a loop.
- Add the new round with push.
const kills = [5, 9, 3, 6];