slice is a JavaScript method used to extract a range of elements from an array or string. Syntax: array.slice(start, end), where start is the starting index (inclusive) and end is the ending index (inclusive). Usage methods include: extracting subarrays/substrings, copying arrays/strings, extracting elements from the beginning/end, and using the step parameter. The operation does not modify the original array and creates a new copy.
The slice method in JS
What is slice?
slice is a built-in method in JavaScript that is used to extract a range of elements from an array or string.
Syntax:
<code class="js">array.slice(start, end)</code>
Among them:
Usage:
The slice method has the following usage:
<code class="js">const arr = [1, 2, 3, 4, 5]; const subArr = arr.slice(1, 3); // [2, 3] const str = "Hello World"; const subStr = str.slice(0, 4); // "Hell"</code>
By omitting the end parameter, slice can copy the entire array or character string.
<code class="js">const arrCopy = arr.slice(); const strCopy = str.slice();</code>
Use negative indexes to extract elements from the beginning or end of an array or string.
<code class="js">const firstTwo = arr.slice(0, 2); // [1, 2] const lastTwo = arr.slice(-2); // [4, 5]</code>
The third parameter step can specify the step size for element extraction. For example, a step of 2 means to extract only even-indexed elements from the array or string.
<code class="js">const evenIndices = arr.slice(0, arr.length, 2); // [1, 3, 5]</code>
Note:
The slice method does not modify the original array or string, but creates a new copy.
The above is the detailed content of How to use slice in js. For more information, please follow other related articles on the PHP Chinese website!