Home  >  Article  >  Web Front-end  >  How to delete specified elements in an array in js?

How to delete specified elements in an array in js?

青灯夜游
青灯夜游Original
2020-10-16 15:33:3931277browse

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;
}

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



 
  
 
  
 
  

数组:mon, tue, wed, thur

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!

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