Detailed Explanation of the Usage of splice Method in JavaScript

  • 2021-07-04 18:10:43
  • OfStack

splice in JavaScript is mainly used to operate arrays in js, including deletion, addition, replacement and so on.

Note: This method will change the original array! .

1. Delete-Used to delete elements, two parameters, the first parameter (where to delete the first item), and the second parameter (the number of items to delete)

2. Insert-Inserts any item element into the array at the specified position. 3 parameters, 1 parameter (insertion position), 2 parameter (0), 3 parameter (insertion item)

3. Replace-Inserts any item element into the array at the specified position, deleting any number of items, 3 parameters. The first parameter (starting position), the second parameter (number of items deleted), and the third parameter (insert any number of items)

Example:

1. Delete function. The first parameter is the position of the first item, and the second parameter is how many to delete.

array. splice (index, num), the return value is the deleted content, and array is the result value.

eg:


<!DOCTYPE html> 
<html> 
<body> 
<script> 
var array = ['a','b','c','d']; 
var removeArray = array.splice(0,2); 
alert(array);// Eject c,d 
alert(removeArray);// The return value is a deleted item, that is, it pops up a,b 
</script> 
</body> 
</html> 

2. Insertion function, the first parameter (insertion position), the second parameter (0), and the third parameter (inserted item)

array. splice (index, 0, insertValue), the return value is an empty array, and the array value is the final result value

eg:


<!DOCTYPE html> 
<html> 
<body> 
<script> 
var array = ['a','b','c','d']; 
var removeArray = array.splice(1,0,'insert'); 
alert(array);// Eject a,insert,b,c,d 
alert(removeArray);// Eject empty  
</script> 
</body> 
</html> 

3. Replacement function, the first parameter (starting position), the second parameter (number of deleted items), and the third parameter (inserting any number of items)

array. splice (index, num, insertValue), the return value is the deleted content, and array is the result value.

eg:


<!DOCTYPE html> 
<html> 
<body> 
<script> 
var array = ['a','b','c','d']; 
var removeArray = array.splice(1,1,'insert'); 
alert(array);// Eject a,insert,c,d 
alert(removeArray);// Eject b 
</script> 
</body> 
</html> 

Related articles: