Home > Web Front-end > JS Tutorial > How to delete the first element of an array in javascript

How to delete the first element of an array in javascript

青灯夜游
Release: 2022-02-07 10:49:07
Original
8671 people have browsed it

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

How to delete the first element of an array in javascript

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)
Copy after login
  • 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);
Copy after login

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:

How to delete the first element of an array in javascript

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

[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!

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