Beginners JavaScript | Arrays
Arrays are at a basic level just a list of things and creating an array is as easy as:
var myArr = [value1,value2,…,valueN];
or to create an empty array:
var myArr = [];
To access the data stored in the array you would put the array name then the number of the item in square brackets, arrays are 0 indexed so the first item would be at [0] for example:
myArr[0]; // the first item in myArr myArr[100]; // the 99th item in myArr myArr[n]; // the n-1th item in myArr provided n is a number
Arrays can also hold nested arrays as below;
myArr = [ [1,2,3] , [4,5] , 6];
Which would give
myArr[0] == [1,2,3]
myArr[1] == [4,5]
myArr[2] == 6
To access the arrays inside myArr you use double square brackets:
myArr[0][0] == 1
myArr[0][2] == 3
myArr[1][0] == 4
Using this method you can nest multiple arrays inside each other.
You can then use these methods to get information from or add information to an array
Methods
method | function | example |
.length | give the number of items in the array | myArr.length |
.pop() | takes the last item from an array | myArr = [1,2,3];
myArr.pop(); // 3 |
.push() | adds an item to an array | myArr.push(4);
// myArr == [1,2,3,4] |
.shift() | takes first item from an array | myArr = [1,2,3];
myArr.shift(); // 1 |
.unshift() | add an item to the start of an array | myArr.unshift(0);
// myArr == [0,1,2,3] |