Home  >  Article  >  Web Front-end  >  How to delete elements from javascript array

How to delete elements from javascript array

青灯夜游
青灯夜游Original
2021-04-01 13:44:586069browse

Javascript method to delete array elements: 1. Use the splice() function, the syntax format "arr.splice (starting position, number of deleted items)"; 2. Use the delete keyword, the syntax format "delete arr [Remove subscript of element]".

How to delete elements from javascript array

The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.

Method 1: Use splice()

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.

Method 2: Use delete

After delete deletes the element in the array, the subscripted value will be set to undefined, and the length of the array will not change.

var arr = ['a','b','c','d'];
delete arr[1];
arr;  
//["a", undefined × 1, "c", "d"] 中间出现两个逗号,数组长度不变,有一项为undefined

For more programming-related knowledge, please visit: Programming Video! !

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