Slice is used to extract a copy of an array without modifying the original array. It returns elements within the specified index range. Splice is used to modify an array. It removes elements from a specified index, inserts new elements, and returns an array of removed elements.
The difference between Slice and Splice in JavaScript
Slice and Splice are both JavaScript array methods, used to extract data from an array Extract or modify elements. They have different functions and usage:
slice()
Syntax: `
js
arr.slice(start, end)
Parameters:
start
: Index to start extraction (inclusive). end
: The index at which the extraction ends (not included). Return value: A copy of the original array, containing the elements within the specified index range.
splice()
Syntax: `
js
arr.splice(index, count, ...items)
Parameters:
index
: Index to start modification. count
: Number of elements to remove (optional). ...items
: New element to be inserted at index (optional). Main difference:
Example:
<code class="js">// 使用 slice() 提取元素 const originalArr = [1, 2, 3, 4, 5]; const copiedArr = originalArr.slice(1, 3); // [2, 3] // 使用 splice() 修改数组 const modifiedArr = originalArr.splice(2, 1, 7); // [1, 2, 7, 4, 5]</code>
The above is the detailed content of The difference between slice and splice in js. For more information, please follow other related articles on the PHP Chinese website!