Home >Web Front-end >JS Tutorial >How to delete specified elements in an array in js?
The method to delete the specified element in the array in js: first loop through the array to get the index value of the specified element, and then use the splice() method according to the index value to delete the element, the syntax "array.splice(index Value,1)".
Detailed explanation of how to delete specified elements in an array in JavaScript:
To delete an element in an array, first Need to determine the index value of the specified element that needs to be deleted.
var arr=[1,5,6,12,453,324]; function indexOf(val){ for(var i = 0; i < arr.length; i++){ if(arr[i] == val){return i;} } return -1; }
After finding the corresponding index value, delete the value corresponding to the element in the array according to the index value
function remove(val){ var index = indexOf(val); if(index > -1){arr.splice(index,1);} }
Example: Delete the "tue" element in the array somearray
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <div class="demo"> <p>数组:mon, tue, wed, thur</p> <p class="p"></p> </div> </body> <script type="text/javascript"> 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" document.write("<p>新数组:" + somearray + "</p>"); </script> </html>
Related free learning recommendations: js video tutorial
The above is the detailed content of How to delete specified elements in an array in js?. For more information, please follow other related articles on the PHP Chinese website!