본문으로 건너뛰기

Array Methods - Slice

Array Methods - Slice

Let's learn how to extract specific parts of an array using slice.


Arrays Start at Index 0, Not 1

In most programming languages, array indexing starts at 0. This is a traditional computing convention.

let fruits = ['apple', 'banana', 'cherry', 'grape', 'orange'];

To access each element of this array, you would do the following:

  • First element: fruits[0] => "apple"

  • Second element: fruits[1] => "banana"

  • Third element: fruits[2] => "cherry" ... (and so on)


Slicing Arrays:

You can use the slice() method of an array to extract parts of it. slice() does not modify the original array but returns a new one.

Basic structure:

array.slice([start index], [end index])
  • Start index: The position in the array where the extraction starts. If omitted, it starts from the beginning of the array.

  • End index: The position in the array just before which to end the extraction. This index is not included. If omitted, it extracts up to the end of the array.


Example:

let fruits = ['apple', 'banana', 'cherry', 'grape', 'orange'];
let selectedFruits = fruits.slice(1, 3);
console.log(selectedFruits); // ["banana", "cherry"]

다음 내용이 궁금하다면?

월 12,500원 PLUS 멤버십 가입 or 강의를 등록해 주세요!