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

How to delete array elements in javascript

青灯夜游
Release: 2023-01-06 11:13:48
Original
4602 people have browsed it

Delete method: 1. The length attribute deletes elements from the end of the array, the syntax is "array name.length=value"; 2. The delete keyword deletes the specified element, the syntax is "delete array name [subscript]"; 3 , splice() function, syntax "array name.splice (starting position, number of deletions)".

How to delete array elements in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

length attribute

The length attribute of Array in JavaScript is very unique—it is not read-only. Therefore, you can set this property to remove an item from the end of an array or to add a new item.

var colors = ["red", "blue", "grey"]; // 创建一个包含3个字符串的数组
colors.length = 2;

console.log(colors[2]); // undefined
Copy after login

delete keyword

JavaScript provides a delete keyword to delete (clear) array elements.

var colors = ["red", "blue", "grey", "green"];
delete colors[0];

console.log(colors); // [undefined, "blue", "grey", "green"]
Copy after login

It should be noted that after using delete to delete an element, the length of the array does not change, but the deleted element is set to undefined.

splice() operation method

The JavaScript Array object provides a splice() method for performing specific operations on the array. . splice() is probably the most powerful array method. It can be used in many ways. Here we only introduce the method of deleting array elements. When deleting array elements, it can delete any number of items by specifying only 2 parameters: the position of the first item to be deleted and the number of items to be deleted.

var colors = ["red", "blue", "grey"];
var color = colors.splice(0, 1);

console.log(color); // "red"
console.log(colors); // ["blue", "grey"]
Copy after login

It can be seen that when the splice(0, 1) method is called, one item is deleted from the array starting from the first item.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to delete array elements 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!