Home > Article > Web Front-end > How to delete any element in an array in javascript
In the previous article, we learned about how to delete the first and last elements of an array. Please see "How to delete the first and last elements of an array in javascript? 》. This time we will learn how to delete any element in an array. You can refer to it if necessary.
We know how to delete the first and last elements of an array, but have you ever thought about how to delete any element in the array? Let’s talk about it this time.
We know that we have talked about a method before, called splice. Do you still remember it? We used this method before to add elements to the array. Today we will use this array to delete elements. Don't look forward to it.
First let’s look at a small example.
<script> var arr = new Array(3); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; console.log(arr); arr.splice(1,1); console.log(arr); </script>
Look at the answer to this example.
#As you can see in this example, our original array has three elements. After using the splice method, "one" in the array is deleted. So let's take a look at this method in detail.
The splice() method is used to add or delete elements in the array, and this method can also be used to modify the elements in the array.
Let’s take a look at the syntax format of this method.
数组名称.splice(规定从何处添加/删除元素,规定应该删除多少元素,要添加到数组的新元素)
If we only write the added elements and do not write the first two parameters, this method will delete all the elements in the array; if the second parameter is 0, it means this method New elements will be added to the array; if you write the first and second parameters but not the third parameter, this means that the splice method will delete elements from the array.
That’s all. If you need it, you can read: javascript advanced tutorial
The above is the detailed content of How to delete any element in an array in javascript. For more information, please follow other related articles on the PHP Chinese website!