프로젝트에서 고정된 길이의 배열을 생성을 하는 경우가 있었다. 리펙토링하면서 내 코드들을 보면서 가독성을 체크하는 과정에서, 내가 작성한 배열 생성 방식이 다소 복잡해 보인다는 느낌을 받았다. 이에 다양한 배열 생성 방법과 그 차이점을 정리해보자
1. 배열 리터럴 (Array Literal)
가장 기본적이고 직관적인 배열 생성 방식
// 0부터 5까지의 숫자를 직접 나열한 배열
const arrLiteral = [0, 1, 2, 3, 4, 5];
참고 : 값 없이 undefined를 채운 배열은 직접 나열하기엔 비효율적임
2. Array 생성자 (Array Constructor)
const arrConstructor = new Array(6);
// 출력: [ <6 empty items> ]
주의 : 이 방식은 "empty slots"를 생성하므로 map 등 배열 메서드를 바로 사용하면 의도한 대로 동작하지 않을 확률이 있음
3. 스프레드 연산자와 Array(n) 결합
빈 슬롯을 가진 배열을 스프레드 연산자로 변환하여 각 슬롯에 undefined가 채워진 배열을 만듬
const arrSpread = [...Array(6)];
// 출력: [undefined, undefined, undefined, undefined, undefined, undefined]
이후 map 함수를 사용해 원하는 값으로 채울 수 있음
4. Array.from 메서드
유사 배열 객체를 기반으로 배열을 생성하며, 두 번째 인자로 매핑 함수를 사용하여 초기값을 지정 가능
// undefined로 채워진 길이 6 배열
const arrFromEmpty = Array.from({ length: 6 });
// 출력: [undefined, undefined, undefined, undefined, undefined, undefined]
// 0부터 5까지의 숫자로 채운 배열
const arrFromSeq = Array.from({ length: 6 }, (_, idx) => idx);
console.log(arrFromSeq); // [0, 1, 2, 3, 4, 5]
5. Array.of 메서드
인자로 전달한 값을 그대로 요소로 취급하는 방식
// 단일 숫자는 요소로 취급하므로, 스프레드 연산자와 결합해서 사용
const arrOf = Array.of(...Array(6));
console.log(arrOf); // [undefined, undefined, undefined, undefined, undefined, undefined]
6. Array.fill 메서드
배열을 생성한 후 fill 메서드로 모든 요소를 특정 값으로 채울 수 있음
const arrFill = Array(6).fill(0);
console.log(arrFill); // [0, 0, 0, 0, 0, 0]
7. Generator 함수와 Array.from 결합
복잡한 로직이 필요할 때는 generator 함수를 만들어 배열로 변환 가능
function* numberGenerator(n) {
for (let i = 0; i < n; i++) {
yield i;
}
}
const arrGen = Array.from(numberGenerator(6));
console.log(arrGen); // [0, 1, 2, 3, 4, 5]
이와 같이 여러 가지 방법으로 고정 길이 배열을 생성할 수 있으며, 상황에 맞게 가장 가독성이 좋고 유지보수하기 쉬운 방법을 선택하면 된다.