Backdrop

프로그래머스 ▸ 코딩 기초 트레이닝

n 번째 원소까지
0

문제 설명

정수 리스트 num_list와 정수 n이 주어질 때, num_list의 첫 번째 원소부터 n 번째 원소까지의 모든 원소를 담은 리스트를 return하도록 solution 함수를 완성해주세요.

제한사항

  • 2 ≤ num_list의 길이 ≤ 30
  • 1 ≤ num_list의 원소 ≤ 9
  • 1 ≤ nnum_list의 길이 ___

입출력 예

num_listnresult
[2, 1, 6]1[2]
[5, 2, 1, 7, 5]3[5, 2, 1]

입출력 예 설명

입출력 예 #1

  • [2, 1, 6]의 첫 번째 원소부터 첫 번째 원소까지의 모든 원소는 [2]입니다.

입출력 예 #2

  • [5, 2, 1, 7, 5]의 첫 번째 원소부터 세 번째 원소까지의 모든 원소는 [5, 2, 1]입니다.

풀이

이론

Array.prototype.slice()

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환해요. 원본 배열은 바뀌지 않아요.

arr.slice([begin[, end]])
  • begin 또는 end 가 음수인 경우, 배열의 끝에서부터의 길이를 나타내요.
  • begin 이 생략된 경우, 0 번째 인덱스부터 추출해요.
  • end 가 생략된 경우, 배열의 끝까지 추출해요.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
 
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
 
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
 
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
 
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

코드

function solution(num_list, n) {
  return num_list.slice(0, n);
}