Appearance
Arrays
JavaScript's Array
can contain any data type and access each element via index.
To get the length of an Array
, simply access the length
property:
javascript
let arr = [1, 2, 3.14, 'Hello', null, true];
console.log(arr.length); // 6
Assigning a new value to the length
property directly will change the size of the Array
:
javascript
let arr = ['A', 'B', 'C'];
arr.length = 6; // arr becomes ['A', 'B', 'C', undefined, undefined, undefined]
arr.length = 2; // arr becomes ['A', 'B']
You can modify an Array
element via its index:
javascript
let arr = ['A', 'B', 'C'];
arr[1] = 99; // arr now becomes ['A', 99, 'C']
If you assign a value to an index that exceeds the current range, it will also adjust the Array
size:
javascript
let arr = ['A', 'B', 'C'];
arr[5] = 'x'; // arr becomes ['A', 'B', 'C', undefined, undefined, 'x']
indexOf
Similar to String
, Array
can use indexOf()
to find the position of a specified element:
javascript
let arr = [10, 20, '30', 'xyz'];
arr.indexOf(10); // returns 0
arr.indexOf(30); // returns -1
slice
slice()
extracts a portion of an Array
and returns a new one:
javascript
let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
arr.slice(0, 3); // returns ['A', 'B', 'C']
push and pop
push()
adds elements to the end, while pop()
removes the last element:
javascript
let arr = [1, 2];
arr.push('A', 'B'); // arr becomes [1, 2, 'A', 'B']
arr.pop(); // returns 'B'
unshift and shift
unshift()
adds elements to the front, while shift()
removes the first element:
javascript
let arr = [1, 2];
arr.unshift('A', 'B'); // arr becomes ['A', 'B', 1, 2]
sort
sort()
modifies the Array
in place to sort elements:
javascript
let arr = ['B', 'C', 'A'];
arr.sort(); // arr becomes ['A', 'B', 'C']
reverse
reverse()
reverses the order of elements:
javascript
let arr = ['one', 'two', 'three'];
arr.reverse(); // arr becomes ['three', 'two', 'one']
splice
splice()
modifies the Array
by removing and adding elements:
javascript
let arr = ['Microsoft', 'Apple', 'Yahoo'];
arr.splice(1, 1, 'Google'); // arr becomes ['Microsoft', 'Google', 'Yahoo']
concat
concat()
merges two Array
s and returns a new one:
javascript
let arr = ['A', 'B', 'C'];
let added = arr.concat([1, 2, 3]); // returns ['A', 'B', 'C', 1, 2, 3]
join
join()
connects all elements into a string:
javascript
let arr = ['A', 'B', 'C', 1, 2, 3];
arr.join('-'); // returns 'A-B-C-1-2-3'
Multi-dimensional Arrays
An element of an Array
can be another Array
, creating multi-dimensional arrays:
javascript
let arr = [[1, 2, 3], [400, 500, 600], '-'];
Summary
Array
provides a way to store a sequence of elements, accessible by index.