Javascript

fill() 메서드

minsun309 2024. 9. 9. 11:06

프로그래머스 코딩테스트 하던 중 자주 쓰지 않았던 fill()메서드를 활용한 경우가 많아 익숙하지 않은 메서드를 학습해보고자 fill()메서드에 대해 정리해보았다.

fill()

fill(value, start, end)

배열의 start index 부터 end index 전까지(end index는 미 포함) value값으로 채워주는 함수이다.

value : 배열에 넣을 값 start : value 값을 채울 배열의 시작 index (기본 값 : 0) end : value 값을 채울 배열의 종료 index로 end는 포함하지 않습니다.  (기본 값 : 배열의 길이)

 

예시

const array = ['a', 'b', 'c', 'd'];
array.fill('A', 1, 3); 
// ['a', 'A', 'A', 'd']

const arr = new Array(4).fill('A');
// ['A', 'A', 'A', 'A']

 

1~20 만들기

20개의 element를 가지는 배열이 생성하고 map 함수를 활용해 각 자리 index에 해당하는 값을 할당하면 된다.

const makeTwenty = Array(20).fill().map((arr, i) => {
    return i+1
})

See the Pen fill() makeTwenty by pminsun (@pminsun) on CodePen.

 

 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

 

Array.prototype.fill() - JavaScript | MDN

Array 인스턴스의 fill() 메서드는 배열의 인덱스 범위 내에 있는 모든 요소를 정적 값으로 변경합니다. 그리고 수정된 배열을 반환합니다.

developer.mozilla.org