Home > Web Front-end > JS Tutorial > body text

How to use slice function in js

下次还敢
Release: 2024-05-06 10:18:16
Original
561 people have browsed it

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].

How to use slice function in js

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>
Copy after login

Parameters:

  • start: Start index (including ). If negative, counting starts from the end of the array.
  • end: Ending index (exclusive). If negative, counting starts from the end of the array.

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>
Copy after login

Features:

  • slice() function does not modify the original array.
  • slice() returns a new array containing the specified elements from start to end.
  • If start or end is outside the range of the array, the function will use the array length or 0 as the actual index.
  • If start and end are equal, the function returns an empty array.
  • If start and end are negative values, the function will start counting from the end of the array.

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!