Home > Article > Web Front-end > Multiple methods to delete elements from JS array
In the content of this article, we will talk about how to delete an element in the array in js. We must be familiar with the continued operation of the array. Friends who don’t know much about it can pay attention. In this article, without further ado, let’s read on!
The following code uses two methods to delete elements of the array:
The first defines a separate function
The second type defines a removeByValue method for Array object
It is very simple to call
1. Define the function removeByValue to delete elements
Example code:
function removeByValue(arr, val) { for(var i=0; i<arr.length; i++) { if(arr[i] == val) { arr.splice(i, 1); break; } } } var somearray = ["mon", "tue", "wed", "thur"] removeByValue(somearray, "tue"); //somearray will now have "mon", "wed", "thur"
Add the corresponding method to the array object, and the call becomes simpler. Directly call the removeBy of the array Value methodYou can delete the specified element
Example code:
Array.prototype.removeByValue = function(val) { for(var i=0; i<this.length; i++) { if(this[i] == val) { this.splice(i, 1); break; } } } var somearray = ["mon", "tue", "wed", "thur"] somearray.removeByValue("tue"); //somearray will now have "mon", "wed", "thur"
The above is the content of this article. Learn the basics now and you will not have a headache in the future. Although the basics are very Whether it is simple or the more solid you learn, the more useful it will be. This article is the basis of typical js array operations. I hope everyone can have a good understanding of it!
Type reading:
JavaScript arrayIntroduction to the method of deleting specific elements
Deleting specified elements from a js array is something that every one of us encounters Question
Implementation of the add, delete, modify and check functions of JavaScript arrays
This article mainly introduces the simple implementation of the add, delete, modify and check functions of JS array operations
The above is the detailed content of Multiple methods to delete elements from JS array. For more information, please follow other related articles on the PHP Chinese website!