Home > Web Front-end > JS Tutorial > body text

How to delete any element in an array in javascript

醉折花枝作酒筹
Release: 2021-08-10 11:27:52
Original
1712 people have browsed it

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>
Copy after login

Look at the answer to this example.

How to delete any element in an array in javascript

#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(规定从何处添加/删除元素,规定应该删除多少元素,要添加到数组的新元素)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!