JS: Array (basics)
- Array is a data structure that holds a sequence of values, in order.
- Each value can be any Value Types.
- Each value is indexed by a integer, starting from 0.
Create array (array literal expression)
[value1, value2, etc]
console.log([1, 2, 3]); // [ 1, 2, 3 ] // elements with mixed types console.log(["one", 3]); // [ "one", 3 ]
Length
xArray.length return the count of elements.
console.log([7, 8, 2].length); // 3
Get an element
via at (method)
// get a element console.log([3, 4].at(0)); // 3 console.log([3, 4].at(-1)); // 4
via bracket operator
xArray[index]
index cannot be negative.
This is the bracket notation for property access. [see JS: Property Dot Notation vs Bracket Notation]
// get a element console.log([17, 4, 1][0]); // 17
Modify array element
const xx = [2, 4, 1]; xx[0] = 99; console.log(xx); // [ 99, 4, 1 ]
🟢 tip: you should not modify array element like this. because it is easy to go out of bound and accidentally create Sparse Array.
Out of bound
if index is out of bound, result is a Sparse Array.
const xx = [0, 1]; xx[4] = 99; console.log(xx); // [ 0, 1, <2 empty items>, 99 ]
Change array element, return new copy
Nested array
Array can be nested.
const xx = [3, [4, 5]]; console.log(xx[1][1]); // 5
Loop over array
for (let x of [3, 4, 5]) { console.log(x); } /* 3 4 5 */
Clear all array elements
const xx = [3, 4, 5]; xx.splice(0); console.log(xx.length); // 0
Note, it's different from simply assign it a new empty array such as
xArray = []
Because that gives the variable xArray a new value.