javascript - fill()

so.oy·2023년 6월 14일
0

Today's Study📚 

목록 보기
2/5
post-thumbnail

Array.prototype.fill()

프로그래머스 문제 중 배열의 원소만큼 추가하기를 풀다가 다음과 같은 풀이를 보게 되었다.

function solution(arr) {
    return arr.reduce((list, num) => [...list, ...new Array(num).fill(num)], []);
}

이 중 fill()함수에 대해서 알아보고, 이 코드에서 fill()함수가 어떻게 동작하는지 알기 위해서 정리해보고자 한다.

MDN 설명에 따르면

fill() 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채우는 메서드이다.

const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]

Array.prototype.fill() - JavaScript | MDN

구문

arr.fill(value[, start[, end]])

매개변수

value

배열에 채울 값을 지정

start

value 값을 채울 배열의 시작 index

입력하지 않으면 기본값은 0.

end

value 값을 채울 배열의 종료 index

입력하지 않으면 기본값은 배열의 길이(arr.length)이다.

예제

arr.fill(’L’, 1, 3)

fill() 메서드는 배열의 start index부터 end index 전까지(end index는 미포함) value값으로 채워주는 함수입니다.

index()가 음수일 때

start나 end index가 음수로 지정되면 배열의 마지막 원소의 index가 -1이 되고,앞으로 올수록 인덱스가 감소한다.

arr.fill(’L’, -3, -1)

fill()을 이용한 배열 초기화

const arr = new Array(5).fill('A');

new Array() 구문을 사용하여 배열을 생성하면,

5개의 element를 가지는 배열이 생성되고,

각 element의 값은 undefined입니다.

여기에 fill() 함수를 사용하면, 생성된 배열의 element의 초기값을 지정할 수 있다.

👉 해당 문제 풀이 보러가기

https://github.com/sooyv/Programmers-Algorithm-JS/commit/7a620cd778abc8fe1685066def96cd6ae717d111

profile
🌱 개발공부로그

0개의 댓글