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

How to delete an element in an array in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-03-31 09:59:392385browse

Javascript method to delete an element in an array: First, you can define a function for the JS array object to find the position of the specified element in the array; then use to get the index of this element, use js The array's own inherent function is used to delete this element.

How to delete an element in an array in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Javascript method to delete an element in an array:

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 the index to get the element, and use the js array's own inherent function to delete the element:

The code is:

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

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

var emp = [&#39;abs&#39;,&#39;dsf&#39;,&#39;sdf&#39;,&#39;fd&#39;]

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

emp.remove(&#39;fd&#39;);

Related free learning Recommended: javascript(Video)

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