In the previous article we learned how to add elements to an array, please see "How to add elements to an array in js". This time we will learn how to delete the first and last elements of an array. You can refer to it if necessary.
We added elements to the array before. This time we want to delete the first and last elements in the array. What should we do? First, let's take a look at how to delete the front (head) element of the array.
Let’s look at a small example first.
var arr = new Array(3); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; console.log(arr); var arrly=arr.shift(); console.log(arrly); console.log(arr);
The result is
#As you can see in this example, our original array has three elements. After using a certain method, the array The header element is deleted. Next, let's take a look at the code. It turns out that the shift method is used, so let's take a look at this method.
The shift() method is used to remove the first element of the array and return the value of the first element.This method will change the length of the array!
After we have introduced the method of deleting the head element of the array, we will introduce the method of deleting the tail element of the array.
Let’s look at a small example first. Let's change the previous code.
var arr = new Array(3); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; console.log(arr); var arrly=arr.pop(); console.log(arrly); console.log(arr);
The result is
You can see this example. There are three elements in our original array and a certain method is used. After that, the tail element of the array is deleted. Next, let's take a look at the code. It turns out that the pop method is used, so let's take a look at this method.
The pop() method is used to delete the last element of the array and return the deleted element.
Importantly,this method will change the length of the array.
Needs to pay attention.
That’s all. If you need it, you can read:javascript advanced tutorial
The above is the detailed content of How to delete the first and last elements of an array in javascript?. For more information, please follow other related articles on the PHP Chinese website!