Manipulating arrays
Table of contents:
Push
Push it a method on an array that added items to the end of the array. So in this code, we’ve created values as a three-element array, and then we’re executing value.push
, and we’re passing it the element that we want to add to the end of the array, the letter d
.
When we log out values, we get a, b, c, c
and d
.
Pop
Method pop
takes the last element off an array. When executing value.pop
we take the last element, in this case, c
, off of the array, and store it in the variable last. When we log out last, we get c
.
Shift
The shift moves the entire array. We can shift of shift()
method as shifting the entire array to the left one element, and it takes the first element off the array. We calling values.shift
, and we’re assigning the result of that to first. The result will be the first element of the array, the letter a
.
Unshift
Starting with an array with values b
and c
and we call values.unshift
, passing it a
. So this added the letter a
to the beginning of the array. When we log out values, we get a
, b
, c
and c
.
Slice
When we execute the value.slice
and we have two arguments. The first argument is where we want to start to take our slice, which is element 1
- (element 1
is b
) it’s not a
, a
is element 0
. Ant to give us the ending element that we want to look at, which is 2
, in which case that would be c
.
Line const newValue = value.slice(1, 2)
creates a new array and that new array is stored in the variable newValue
. When we log out newValue
we get our slice, which is only item b
. The item at index 2
, the end position is not including in the results. It essentially made a copy of the slice of the array without altering the original.
Splice
When we execute value.splice
with two arguments. The first argument is the index of the element we want to delete, and the second argument is the number of items we want to delete.
So index 1
is the b
and let’s just delete that b
by specifying one item. When we log out values, we got a
and c
. The b
is gone. Splice can be used for inserting. For example:
Reference:
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.