Home > Web Front-end > JS Tutorial > body text

How to delete an item in js array

青灯夜游
Release: 2023-01-05 16:14:17
Original
108677 people have browsed it

How to delete an item in a js array: 1. Use the splice() function to delete, the syntax format is "array.splice (the starting subscript of the deleted element, 1)"; 2. Use the delete keyword, the syntax Format "delete array[array element index]".

How to delete an item in js array

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to delete an item in an array in js

1. Use the splice() function

In JS, you can use the splice() function to delete an item in the array; the splice() method is used to add or delete elements in the array.

Syntax:

splice(index,len,[item])
Copy after login

Comments: This method will change the original array.

splice has 3 parameters, it can also be used toreplace/delete/addone or several values ​​in the array

  • index: Array start subscript                                                                                                                                             

  • For example: arr = ['a','b','c','d']

  • Delete---- item is not set
  • arr.splice(1,1)   //['a','c','d']         删除起始下标为1,长度为1的一个值,len设置的1,如果为0,则数组不变
    arr.splice(1,2)  //['a','d']          删除起始下标为1,长度为2的一个值,len设置的2
    Copy after login

    Description: If only one element is deleted, an array of one element is returned. If no elements were removed, an empty array is returned.

2. Use delete keyword

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

delete arr[1] //[‘a’, ,‘c’,‘d’] 中间出现两个逗号,数组长度不变,有一项为undefined
Copy after login
For more programming-related knowledge, please visit:

Introduction to Programming

! !

The above is the detailed content of How to delete an item in js array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!