Home > Article > Web Front-end > How to delete specified elements in an array in javascript
JS deleting the specified element in the array is mainly divided into two steps. First, determine whether the array contains the element, and then delete the specified element through the splice() method.
This article mainly introduces how The method of deleting specified elements in an array through JavaScript language has a certain reference effect. I hope it will be helpful to everyone.
[Recommended course: javascript tutorial]
JavaScript deleting specified elements in an array is generally divided into two In this step, first determine whether the specified element exists in the array, and then delete the element in the array. Next, in this article, I will introduce you to the detailed steps of deleting specified elements in an array using JavaScript.
1. Determine whether the element is in the array
First we need to use JavaScript code to determine whether the element we want to delete is in the array. We can do the following Method to achieve this function
function isInArray(arr,value){ for(var i = 0; i < arr.length; i++){ if(value === arr[i]){ return true; } } return false; }
Through the above method, you can define a function to determine whether the specified element is in the array. If it is in the array, it will return true, if it is not in the array, it will return false
We can also use the indexOf method to determine whether the specified element is in the array
function IsInArray(arr,val){ var testStr=','+arr.join(",")+","; return testStr.indexOf(","+val+",")!=-1; } var arr=["sdf","ddd","eds","enm"]; console.log(IsInArray(arr, "eds"));
There are two points to note when using the indexOf method. One is that the O in the indexOf method must be capitalized, and the other is that this method works in IE browsers. This method does not exist in the array
Rendering:
##2. Delete the specified element in the array
After finding the index of the element to be deleted, delete the element through the following function methodThe realization of this function is mainly realized through the splice() method, which is mainly used for Delete, replace, add elements in the array, etc.Example:
<script> function removeArray(arr, val) { for(var i = 0; i < arr.length; i++) { if(arr[i] == val) { arr.splice(i, 1); break; } } } var arr=["sdf","ddd","eds","enm"]; removeArray(arr, "eds"); document.write("<p>删除后的数组:" + arr + "</p>"); </script>
Rendering:
The above is the detailed content of How to delete specified elements in an array in javascript. For more information, please follow other related articles on the PHP Chinese website!