JavaScript Glossary: Array .slice() Method

Publikováno: 8.2.2019

Basics

The slice array method copies a given part of an array returning the selected part as an array. It doesn’t mutate the given array rather, it returns a new array.

<...

Celý článek

Basics

The slice array method copies a given part of an array returning the selected part as an array. It doesn’t mutate the given array rather, it returns a new array.

[1, 2, 3, 4, 5].slice(1)
// [2, 3, 4, 5]

https://scotch.io/embed/gist/e263c9b3a0bc6d72391c694fd40bece3

Syntax

array.slice(start, end)

2 Parameters

start This is the start index for the slice selection. The slice will start from the element at the provided index. If just the start index is provided and no end index is provided, the returned array will contain elements from the start index to the end of the array - optional.

end This is the end index for selection. All the elements from the start index to the element before the end index are selected - optional

Returns an array

The method will return an array containing all the elements from the start index to the element before the end index. If no arguments are provided, it will return an array containing the elements in the parent array.

const numbers = [2, 3, 4, 5, 6];
const sliced = numbers.slice(2,4);
console.log(sliced);

//output: Array [4,5]

Common Usage and Snippets

Getting a selected part of an array

https://scotch.io/embed/gist/395c9706381a8328340cde62d9779b25

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace