Home  >  Article  >  Web Front-end  >  array javascript delete

array javascript delete

PHPz
PHPzOriginal
2023-05-05 22:49:08646browse

Array in JavaScript is a very commonly used data structure that can store multiple elements. If you need to delete elements from an array, there are several ways to do it. This article focuses on how to use the methods provided in JavaScript to delete array elements.

First of all, there are several main methods to delete array elements in JavaScript, including splice(), pop(), and shift(). They are introduced below.

  1. splice()

The splice() method can add/remove elements in the array at the same time. This method accepts 3 parameters:

  • The starting position index of the element to be deleted (starting from 0)
  • The number of elements to be deleted
  • (optional) Elements to be added to the array

Sample code:

let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // 删除起始位置为2的元素(也就是第3个元素)
console.log(arr); // [1, 2, 4, 5]

In the above code, arr.splice(2, 1) means to delete the arr array 1 element starting from the element at index position 2 (that is, the third element), so the final array becomes [1, 2, 4, 5].

If you need to add elements to the array, just pass them as the 3rd and 4th... parameters of the splice() method. For example:

let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, 6, 7); // 删除起始位置为2的元素,同时添加6和7元素
console.log(arr); // [1, 2, 6, 7, 4, 5]

In the above code, the splice() method deletes the element with starting position 2 (that is, 3) and adds elements 6 and 7 to the array.

  1. pop()

The pop() method removes the last element from the array and returns the removed element. If the array is empty, undefined is returned.

Sample code:

let arr = [1, 2, 3, 4, 5];
let deleted = arr.pop(); // 删除最后一个元素(5),deleted为删除的元素
console.log(arr); // [1, 2, 3, 4]
console.log(deleted); // 5
  1. shift()

The shift() method removes the first element from the array and returns the deleted element. If the array is empty, undefined is returned.

Sample code:

let arr = [1, 2, 3, 4, 5];
let deleted = arr.shift(); // 删除第一个元素(1),deleted为删除的元素
console.log(arr); // [2, 3, 4, 5]
console.log(deleted); // 1

Summary

The above are the three ways to delete array elements in JavaScript.

If you want to delete elements at any position, you can use the splice() method; if you only need to delete the last element, you can use the pop() method; if you only need to delete the first element, you can use shift() method.

Hope this article is helpful to you!

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