Home > Article > Web Front-end > How to delete the first element of an array in javascript
Javascript method to delete the first few elements of an array: 1. Use splice(), the syntax "array.splice (specified position index, 1)"; 2. Use the delete keyword, the syntax "delete array name [ Specify location index]".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript method to delete the first few elements of an array
1. Use the splice() method
The JavaScript Array object provides a splice() method for performing specific operations on arrays. 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.
Syntax for deleting elements:
array.splice(index,howmany)
The first parameter index can specify the starting subscript position (that is, the position where the element is deleted);
The second parameter howmany specifies the number of elements that should be deleted (that is, one or more elements that need to be deleted).
Let’s take a closer look at the following example:
var arr= [1,2,3,4,5]; console.log(arr); arr.splice(1,1); console.log(arr);
It can be seen that: use arr.splice(1,1)
from the following Starting from the position marked 1 (the second element of the array), one element is deleted, that is, arr[1] is deleted, so the output result is:
2 ,Using the 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.
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to delete the first element of an array in javascript. For more information, please follow other related articles on the PHP Chinese website!