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

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

青灯夜游
青灯夜游Original
2021-09-16 15:58:4641972browse

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) 

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

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

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']
    spice replaced:
  • arr.splice(1,1,'str'); //结果arr=['a','str','c','d']
    spice Replacement 2:
  • arr.splice(1,2,'str'); //结果arr=['a','str','d'](就是说:下标1开始2个换成1个“str”)
    spice Delete multiple:
  • arr.splice(1,2); //结果arr=['a','d']

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

delete arr[index];
Example:

delete arr[1];

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]);

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!

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