JavaScript: Array Basics
Array is a data structure that holds a sequence of values, in order.
Each value is βindexedβ by a integer, starting from 0.
Creating Array
The basic syntax to create a array is: [expr0, expr1, expr2, etc]
.
const aa = ["one", "two", 3]; console.log(aa); // [ 'one', 'two', 3 ]
Example of assigning array items one at a time:
// define a empty array const aa = []; // assign a value to a slot aa[0] = 82; aa[1] = 34; aa[3] = 96; console.log(aa); // [ 82, 34, <1 empty item>, 96 ] // value of aa[2] do not exist
Creating a Array with n Elements
There are many ways to create a array with 1 to n elements. Most common way is by for Loop
// create array with elements 1 2 3 ... n const aa = []; for (let i = 1; i <= 5; i++) aa.push(i); console.log(aa); // [ 1, 2, 3, 4, 5 ]
Array Length
arrayX.length
return the count of elements.
console.log([7, 8, 2].length === 3);
Access Array Element
Access a element. arrayX[index]
const aa = [2, 4, 1]; // access a element console.log(aa[0] === 2);
Modify Array Element
Modify a element.
const aa = [2, 4, 1]; aa[0] = "no"; console.log(aa); // [ 'no', 4, 1 ]
Nested Array
Array can be nested.
const aa = [3, [4, 5]]; console.log(aa[1][1] === 5);
Loop thru Array
Best way to loop thru array is by using for-of Loop loop.
// for-of loop on array let aa = [3, 4, 5]; for (let x of aa) { console.log(x); } // prints 3 4 5
Here is for-of Loop with index and value:
// for-of loop on array let aa = ["a", "b", "c"]; for (let [i, x] of aa.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 aa = [3, 7, 4]; for (let i = 0; i < aa.length; i++) { console.log(aa[i]); }
Other common way of going thru a array is array methods
forEach
and map
.