Javascript removes array elements and reduces the array length

  • 2020-03-30 01:45:49
  • OfStack

Examples are as follows:



Array.prototype.deleteValue = function(value){
 var i = 0;
 for(i in this){
  if(this[i] == value) break;
 }
 return this.slice(0, i).concat(this.slice(parseInt(i, 10) + 1));
}
// The sample 
var test = new Array(1,5,3,4,2);
//The output of 5
console.log(test.length);
//Delete an element with a value of 4
test = test.deleteValue(4);
//Output [1, 5, 3, 2]
console.log(test);
//The output of 4
console.log(test.length);

Array.prototype.deleteIndex = function(index){
 return this.slice(0, index).concat(this.slice(parseInt(index, 10) + 1));
}
// The sample 
var test = new Array(1,5,3,4,2);
//The output of 5
console.log(test.length);
//Deletes an element with an index of 1
test = test.deleteIndex(1);
//Output [1, 3, 4, 2]
console.log(test);
//The output of 4
console.log(test.length);


Related articles: