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]
const xx = ["one", "two", 3]; console.log(xx); // [ "one", "two", 3 ]
Create Array with n Elements
// create array with 4 elements, all 0 const xx = Array(4).fill(0); console.log(xx); // [ 0, 0, 0, 0 ]
// create array with element 0 to 3 const xx = Array(4).fill(0).map((x,i) => x+i); console.log(xx); // [ 0, 1, 2, 3 ]
Length
myArray.length
return the count of elements.
[7, 8, 2].length === 3
Get an Element
myArray.at(index)
- index can be negative. means count from right.
- JS: Array.prototype.at
const xx = [2, 4, 1]; // get a element console.log(xx.at(0) === 2);
or
myArray[index]
index cannot be negative.
const xx = [2, 4, 1]; // get a element console.log(xx[0] === 2);
Modify Array Element
Modify a element.
const xx = [2, 4, 1]; xx[0] = "no"; console.log(xx); // [ 'no', 4, 1 ]
Nested Array
Array can be nested.
const xx = [3, [4, 5]]; console.log(xx[1][1] === 5);
Loop Over Array
use for-of Loop
// for-of loop on array let xx = [3, 4, 5]; for (let x of xx) { console.log(x); } // prints 3 4 5
Here is for-of Loop with index and value:
// for-of loop on array let xx = ["a", "b", "c"]; for (let [i, x] of xx.entries()) { console.log(i, x); } // prints // 0 'a' // 1 'b' // 2 'c'
The most general purpose way to go thru array is using “for” loop.
// loop thru array const xx = [3, 7, 4]; for (let i = 0; i < xx.length; i++) { console.log(xx[i]); }
Other common way of going thru a array is array methods
forEach
and map
.
Clear All Array Elements
To clear all array elements, use JS: Array.prototype.splice
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
myArray = []
Because that gives the variable myArray a new value.