Arrays come with many built-in methods, and I just learn six most simple methods that can make our life easier.
Push
We use push to add to the end of an array.
For example, if I want to add another letter at the end of array, instead of write letters[4], I can write:
Image an array contains 100+ data, we don’t have to count index every time we want to add a new data in the array.
Pop
We use pop to remove the last item in an array.
If I want to remove the letter “D” from the array, I can write:
Unshift
We use unshift to add a new item to the front of an array.
Instead of add letter “E” at the end of the array, I can add “E” in front of the “A”.
Shift
We use shift to remove the first item in an array.
If I want to remove the letter “A” in the array, I can write:
IndexOf()
We use indexOf() to find the index of an item in an array.
If I want to find the index of letter “C”, I can write:
It gives us the index of “C” is 2. If I want to find an element which is not present in the array such as “M”, it will return as -1.
Slice
We use slice() to copy parts of an array.
If I want to use slice to copy the 2nd and 3d letters which are “B” and “C”, I need to specify index where the new array starts (1 “B”) and ends (3 “D”).
It won’t alter the original letter array. If we want to copy the entire array, we can just write:
var seondLetters = letters.slice();
网友评论