The JavaScript slice() function extracts the specified range of elements from the array through the arr.slice(start, end) syntax and returns a new array without modifying the original array. It accepts two parameters: start (start index, inclusive) and end (end index, exclusive), where start and end can be negative values, indicating that counting starts from the end of the array. If only one argument is provided, end defaults to the array length. Example: arr.slice(1, 3) extracts elements [2, 3] from array [1, 2, 3, 4, 5].
JavaScript slice() function usage
slice() function extracts the specified range of elements from the array and returns a new array.
Syntax:
<code class="javascript">arr.slice(start, end)</code>
Parameters:
Usage:
The slice() function accepts two parameters, indicating the range of elements to be extracted. If only one argument is provided, end defaults to the length of the array.
Example:
Create an array and use slice() to extract elements:
<code class="javascript">const arr = [1, 2, 3, 4, 5]; // 提取从索引 1 到 3 的元素(不包括索引 3) const slicedArr = arr.slice(1, 3); console.log(slicedArr); // 输出: [2, 3]</code>
Features:
The above is the detailed content of How to use slice function in js. For more information, please follow other related articles on the PHP Chinese website!