Home >Web Front-end >JS Tutorial >How to delete array elements in javascript

How to delete array elements in javascript

青灯夜游
青灯夜游Original
2021-05-18 11:40:034731browse

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

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"]

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"]

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!

Statement:
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