Arrays
- One way we can create an array is to use an array literal. An array literal creates an array by wrapping items in square brackets
[]
Arrays in JavaScript are zero-indexed, meaning the positions start counting from
0
rather than1
.
One of an array’s built-in properties is
length
and it returns the number of items in the array.
EX:
console.log(objectives.length);- One method,
.push()
allows us to add items to the end of an array.
EX:
- Another array method,
.pop()
, removes the last item of an array.
EX: chores.pop();
- Some arrays methods that are available to JavaScript developers include:
.join()
,.slice()
,.splice()
,.shift()
,.unshift()
, and.concat()
amongst many others. Using these built-in methods make it easier to do some common tasks when working with arrays. - use
.slice()
to provid a list of things, use index in the code
EX: console.log(groceryList.slice(1, 4));
- find the index of a particular element in
groceryList
using.indexOf()
.
EX: const pastaIndex = groceryList.indexOf('pasta');
FULL EXAMPLE
In order to find the target, put the index of the three different brackets then inside of the brackets.
I learned
- Arrays are lists that store data in JavaScript.
- Arrays are created with brackets
[]
. - Each item inside of an array is at a numbered position, or index, starting at
0
. - We can access one item in an array using its index, with syntax like:
myArray[0]
. - We can also change an item in an array using its index, with syntax like
myArray[0] = 'new string'
; - Arrays have a
length
property, which allows you to see how many items are in an array. - Arrays have their own methods, including
.push()
and.pop()
, which add and remove items from an array, respectively. - Arrays have many methods that perform different tasks, such as
.slice()
and.shift()
- Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
- Variables that contain arrays can be declared with
let
orconst
. Even when declared withconst
, arrays are still mutable. However, a variable declared withconst
cannot be reassigned. - Arrays mutated inside of a function will keep that change even outside the function.
- Arrays can be nested inside other arrays.
- To access elements in nested arrays chain indices using bracket notation.
No comments:
Post a Comment