Home > Web Front-end > JS Tutorial > How to delete elements with specified subscript in an array using javascript

How to delete elements with specified subscript in an array using javascript

青灯夜游
Release: 2023-01-11 09:20:36
Original
42005 people have browsed it

Javascript method to delete specified subscript elements in an array: 1. Use the splice() method of the array, the syntax "arr.splice(index, 1)"; 2. Use the delete keyword, the syntax "delete arr [index]".

How to delete elements with specified subscript in an array using javascript

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

Assume that the array arr has n elements, and now you want to delete the element whose subscript is index

There are two methods:

  • Use the array's splice() method

  • Use delete keyword

##1. splice: After deletion, the following elements are automatically filled in Go to the front

arr.splice(index, 1) 
Copy after login

Example:Now there is an array arr=['a','b','c','d']

arr.splice(1, 1); //结果arr=['a','c','d'](下标1开始,删除1个)
Copy after login

Note:

In the above code, we should pay attention to that if we want to modify the value of arr, just operate arr like this and it will change directly. Instead of writing

arr= arr.splice(1,1), because the return value of the splice() method is the deleted element.

Added:

    spice added:
  • arr.splice(1,0,'str'); //结果arr=['a','str','b','c','d']
    Copy after login
    spice replaced:
  • arr.splice(1,1,'str'); //结果arr=['a','str','c','d']
    Copy after login
    spice Replacement 2:
  • arr.splice(1,2,'str'); //结果arr=['a','str','d'](就是说:下标1开始2个换成1个“str”)
    Copy after login
    spice Delete multiple:
  • arr.splice(1,2); //结果arr=['a','d']
    Copy after login

2. delete: After deletion, The subscript position element is undefined

delete arr[index];
Copy after login

Example:

delete arr[1];
Copy after login

How to delete elements with specified subscript in an array using javascript

The gap element can be read and written, and the length attribute does not exclude gaps. The return value of the empty element bit is undefined

console.log(arr[1]);
Copy after login

How to delete elements with specified subscript in an array using javascript

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to delete elements with specified subscript in an array using javascript. 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