乐闻世界logo
搜索文章和话题

Explaining the Functionality and Usage of splice() and slice()

浏览0
2月7日 16:44

Both splice() and slice() are methods in JavaScript used for handling arrays, but they have different functionalities and usage.

splice()

splice() modifies the array by deleting, replacing, or adding elements at specified positions. The basic syntax is as follows:

javascript
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  • start: Specifies the starting index for modification.
  • deleteCount: (optional) integer indicating the number of elements to delete from the array.
  • item1, item2, ...: (optional) new elements to add to the array.

Example:

javascript
let myArray = ['a', 'b', 'c', 'd']; myArray.splice(1, 2, 'x', 'y'); // Deletes two elements starting at index 1 and inserts 'x' and 'y' console.log(myArray); // Output: ['a', 'x', 'y', 'd']

slice()

slice() returns a new array containing a portion of the original array, from the start index to (but not including) the end index. The original array remains unchanged. The basic syntax is as follows:

javascript
array.slice(begin[, end])
  • begin: Specifies the starting index for extraction (elements from this index are included).
  • end: (optional) Specifies the ending index for extraction (elements up to but not including this index are extracted).

Example:

javascript
let myArray = ['a', 'b', 'c', 'd']; let newArray = myArray.slice(1, 3); // Extracts elements from index 1 to index 2 (i.e., 'b' and 'c') console.log(newArray); // Output: ['b', 'c'] console.log(myArray); // Original array remains unchanged: ['a', 'b', 'c', 'd']

In summary, splice() is a method that modifies the original array by adding or removing elements at any position, whereas slice() creates a new array containing a portion of the original array without altering it.

标签:前端ES6