JS: Array Tutorial
- 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
The basic syntax to create a array is:
[value1, value2, etc]
console.log([1, 2, 3]); // [ 1, 2, 3 ] // elements with mixed types console.log(["one", 3]); // [ "one", 3 ]
Create Array with n Elements
// create array with 4 elements, all 0 console.log(Array(4).fill(0)); // [ 0, 0, 0, 0 ]
// create array with element 0 to 3 console.log(Array(4).fill(0).map((x,i) => x+i)); // [ 0, 1, 2, 3 ]
Length
xArray.length
return the count of elements.
[7, 8, 2].length === 3
Get an Element
via at (method)
xArray.at(index)
- index can be negative. means count from right.
- JS: Array.prototype.at
// get a element console.log([2, 4, 1].at(0) === 2); // true console.log([2, 4, 1].at(-1) === 1); // true
via bracket operator
xArray[index]
index cannot be negative.
// get a element console.log([2, 4, 1][0] === 2); // true
Modify Array Element
const xx = [2, 4, 1]; xx[0] = 99; console.log(xx); // [ 99, 4, 1 ]
Nested Array
Array can be nested.
const xx = [3, [4, 5]]; console.log(xx[1][1] === 5);
Loop Over Array
for-of Loop
// for-of loop on array let xx = [3, 4, 5]; for (let x of xx) { console.log(x); } /* 3 4 5 */
// for-of loop on array. with index and value let xx = ["a", "b", "c"]; for (let [i, x] of xx.entries()) { console.log(i, x); } /* 0 a 1 b 2 c */
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.