Home>Article>Web Front-end> How to delete an element in an array in js

How to delete an element in an array in js

青灯夜游
青灯夜游 Original
2021-03-02 11:30:44 23703browse

JS method to delete an element in an array: first get the position of the specified element in the array (i.e. index index); then use the splice() function to delete the element in the array based on the index value, the syntax format is " splice(index, 1)".

How to delete an element in an array in js

The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.

First, you can define a function for the JS array object to find the position of the specified element in the array, that is, the index. The code is:

Array.prototype.indexOf = function(val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) return i; } return -1; };

Then use to get the index of this element. , use the inherent function of the js array to delete this element:

Array.prototype.remove = function(val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); } };

Related recommendations:JavaScript video tutorial

In this way, such a function is constructed. For example, I have An array:

var emp = ['abs','dsf','sdf','fd']

If we want to delete the 'fd' in it, we can use:

emp.remove('fd');

For more programming-related knowledge, please visit:Introduction to Programming! !

The above is the detailed content of How to delete an element in an array in js. 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