Home >Web Front-end >JS Tutorial >How to use slice in js

How to use slice in js

下次还敢
下次还敢Original
2024-05-01 04:12:15585browse

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.

How to use slice in js

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:

  • start: The starting index of the extracted element (inclusive).
  • end: The end index of the extracted element (exclusive).

Usage:

The slice method has the following usage:

  • Extract a subarray or substring:
<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>
  • Copy an array or string:

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>
  • Extract elements from the beginning or end:

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>
  • Use the step parameter:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn