An array 数组 holds a list of values in order, inside square brackets. Each item is an element 元素, and the first index is 0:
const scores = [72, 88, 95];
console.log(scores[0]); // 72
console.log(scores.length); // 3
scores[1] = 90; // change one element
console.log(scores); // [72,90,95]
const stops you giving scores a whole new array, but you can still change what is inside it.
- Reading past the end gives
undefined: scores[3] is undefined.
Add and remove at the end with push and pop:
const queue = ["Ann", "Ben"];
queue.push("Cai"); // add to the end
console.log(queue); // ["Ann","Ben","Cai"]
const last = queue.pop(); // remove from the end and return it
console.log(last); // Cai
console.log(queue.length); // 2
An array can hold arrays. That makes a grid, read with two indexes, row first:
const grid = [
[1, 2, 3],
[4, 5, 6],
];
console.log(grid[1][2]); // 6 (row 1, column 2)
To visit every element, use a for...of loop. It gives you each value in turn, so you need no index:
const marks = [12, 7, 15];
let total = 0;
for (const m of marks) {
total += m;
}
console.log(total); // 34
An array variable holds a reference 引用 to the array, not a copy. const b = a gives the same array a second name, so a change through b also shows in a. Use [...a] when you want a real copy:
const a = [1, 2, 3];
const b = a; // same array, two names
b.push(4);
console.log(a); // [1,2,3,4]
const c = [...a]; // a new array with the same values
c.push(5);
console.log(a.length, c.length); // 4 5
Two more methods you will use often: slice copies part of an array, and join turns it into one string.
const words = ["red", "green", "blue"];
console.log(words.slice(0, 2)); // ["red","green"] (stops before index 2)
console.log(words.join(" - ")); // red - green - blue