Difference between slice of method and splice of in native JS

  • 2021-07-26 06:45:35
  • OfStack

The slice () method and the splice () method are both methods of manipulating arrays in native js. So what's the difference between the two? Today, I will give you a brief introduction through this tutorial.

slice (), which returns a new array, returns the selected element from an existing array. For example, arrObject (start, end) and start are required. Specify where to start selection. If it is negative, it is selected from the tail of array elements, that is,-1 refers to the last element and-2 refers to the penultimate element; end is an optional element. Specify where to end the selection. This parameter does not, which means truncating from the beginning to the end of the array. If it is negative, it means truncating elements forward from the end of the array. This method does not modify the original array. If you want to delete a 1-segment element in the array, use the splice () method.

splice (), add/delete elements from the array. For example: arrayObject. splice (index, howmany, item1,..., itemX). index is required and specifies where to add/delete items. howmany required, indicating the number of items deleted, and 0 means no element deleted. splice () deletes howmany elements starting with index and can replace deleted elements with item elements. item optional parameter that represents the newly added item.

Usage such as:

(1):


var arr = new Array(5);
arr[0] = "amy";
arr[1] = "elice";
arr[2] = "divi";
arr[3] = "lvy";
arr[4] = "marry";
arr.splice(1, 0, "willian");
console.log(arr);
// Output: amy , willian,elice,divi,lvy In the array section 1 Position increase 1 Elements whose value is "willian"

(2):


var arr = new Array(5);
arr[0] = "amy";
arr[1] = "elice";
arr[2] = "divi";
arr[3] = "lvy";
arr[4] = "marry";
arr.splice(1, 2, "willian");
console.log(arr);
// Output: amy , willian,lvy From the array of the 1 Delete two elements from the position of, and use the new element " willian "Replaces the deleted element. 

Related articles: