Arrays
Array data is ordered by indexes. Arrays are actually objects, having indexes (numbers from 0
to length -1
) as keys.
let fruits = ['apples', 'pears', 'oranges'];
fruits[1]
→ "pears"
Arrays: Access, Add, Remove, and Update Elements
▸ let fruits = ['Apple']
▸ fruits.push('Pear') // Add to the end of the array
2 // The new length of the array
['Apple', 'Pear']
▸ fruits.unshift('Orange') // Add to the start of the array
3 // New length of the array
['Orange', 'Apple', 'Pear']
▸ fruits[1] // Access second element of the array
'Apple'
▸ fruits.length // How many items are in the array?
3
▸ fruits[1] = 'Lemon' // Changes item in index 1 to "Lemon"
"Lemon"
['Orange', 'Lemon', 'Pear']
▸ fruits.splice(1, 0, 'Grapes') // Insert at index 1 a new element
[] // < Splice is supposed to delete things (see below)
// In this case we're deleting 0 elements and inserting one.
['Orange', 'Grapes', 'Lemon', 'Pear']
▸ fruits.indexOf('Lemon') // Get the index of 'Lemon'
2
▸ fruits.splice(2, 1) // Delete 1 item from index 2
["Lemon"]
['Orange', 'Grapes', 'Pear']
▸ fruits.pop() // Remove the last item
"Pear"
['Orange', 'Grapes']
▸ fruits.shift() // Remove the first item
"Orange"
['Grapes']
Iterating over Arrays
var arr = [42, 7, -1]
// Using for-loop
for (var index = 0; index < arr.length; ++index) {
// Do something
}
// Using forEach
arr.forEach((current, index, inputArray) => {
// Do something
})
// Using for...of
for (let current of arr) {
// Do something
}