[프로그래머스/Lv.0] 배열 자르기

Lainlnya·2023년 2월 10일
0

프로그래머스

목록 보기
22/49
post-thumbnail

문제 설명

정수 배열 numbers와 정수 num1, num2가 매개변수로 주어질 때, numbers의 num1번 째 인덱스부터 num2번째 인덱스까지 자른 정수 배열을 return 하도록 solution 함수를 완성해보세요.

제한 사항

  • 2 ≤ numbers의 길이 ≤ 30
  • 0 ≤ numbers의 원소 ≤ 1,000
  • 0 ≤num1 < num2 < numbers의 길이

입출력 예

문제 풀이

function solution(numbers, num1, num2) {
  return numbers.slice(num1, num2 + 1);
}

추가 설명

아주 간단한 문제로 처음에는 splice 메서드를 사용해서 문제를 풀었는데, splice 메서드를 사용할 경우 제출했을 때 60점 밖에 결과를 얻지 못했다. 그래서 고민하다가 slice와 splice 메서드의 차이점에 대해 알게 되었다.

splice(start, deleteCount)
시작 위치와 삭제할 element의 개수 -> 즉, 삭제

  var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
  var removed = myFish.splice(3, 1);

  // removed is ["mandarin"]
  // myFish is ["angel", "clown", "drum", "sturgeon"]

slice(start, end)
start부터 end까지의 배열을 추출

let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

즉, 여기서 splice를 썼다면, num1부터 num2+1개를 자른 결과가 return 됐을 것이기 때문에 slice를 이용해서 num1인덱스부터 num2인덱스까지 자르는 것이 올바르다.

출처 :
Array.prototype.slice()
Array.prototype.splice()

profile
Growing up

0개의 댓글