Home > Web Front-end > JS Tutorial > body text

How to delete specified elements in an array in js?

青灯夜游
Release: 2020-10-19 11:11:57
Original
31456 people have browsed it

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)".

How to delete specified elements in an array in js?

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;
}
Copy after login

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);}
}
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template