[]
, [1, 2, 3]
or [1, [3, 4]]
.arr[2]
. Indexing starts at 0.
arr[5] = 2
. You can set values out of bounds!The length of an array is one more than the largest numeric property.
let a = [1, 4, 5];
a[2]; // 2 -> 5
a[6] = 2;
a;
a.length; // 7
a.foo = 5; // A random property.
The most basic way to iterate over an array’s elements is with a for
loop:
let a = [1,2,3,4];
for (let i = 0; i < a.length; i += 1) {
console.log(a[i]);
}
A better way to iterate over an array, or in fact any iterable object (we will discuss those later), with a for-of
loop, which is similar to Python loops:
let arr = [3,5,3,4];
for (let x of arr) {
console.log(x);
}
// Can use const if you don't try to reassign it in the loop
for (const x of arr) {
console.log(x);
}
Practice: Create an array containing the squares of the numbers from 1 to 10. Then write a loop that prints them.
Consult individual method pages as well as section 7.8 from the book.
Iterators:
for (const i of [2,3,5].keys()) { console.log(i); }
for (const e of [2,3,5].values()) { console.log(e); }
for (const [i, e] of [2,3,5].entries()) { console.log(i + ": " + e); }
Inserting/Removing elements:
Slicing:
Finding:
Others:
There is another set of methods following a higher-order-function paradigm. We will discuss these in future segments.