yunicornlab

[JavaScript 배열 메서드] 자바스크립트 배열 메서드 - 생성 본문

Development/JavaScript

[JavaScript 배열 메서드] 자바스크립트 배열 메서드 - 생성

yunicornlab 2025. 3. 12. 03:32

배열을 생성하는 방법 - 생성자, from, of, fill, copyWithin, with

📌 생성자

생성자 Array()를 통해 새로운 Array 인스턴스를 생성할 수 있다.

new를 붙이지 않아도 Array()는 정상적으로 동작하지만, 일부 특수한 경우에는 new를 생략할 시 예기치 않은 결과가 나올 수 있고 

명확성을 위해 new Array()를 사용하는 것이 좋다.

new Array(요소들... 또는 길이)

 

하나의 숫자만 전달하면 길이만 설정된 빈 배열이 생성되고,

여러개의 요소를 전달하면 해당 요소들로 이루어진 배열이 생성된다.

매개변수 없이 new Array()만 사용하면 빈 배열이 생성된다.

const arr1 = new Array(5);
console.log(arr1); // [ <5 empty items> ] (비어 있는 5칸짜리 배열)
console.log(arr1.length); // 5

const arr2 = new Array(1, 2, 3);  // 요소가 1, 2, 3인 배열

const arr3 = new Array("2"); // 숫자 2가 아니라 문자열 "2"
console.log(arr3.length); // 1
console.log(arr3[0]); // "2"

 

빈 값인 상태에서는 map()이나 forEach()가 정상 동작하지 않기 때문에 fill을 사용해서 초기화하는 게 좋다.

 

⏳ 시간 복잡도 O(1)이다. (fill로 초기화하는 경우는 O(N))

 

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

 

Array() 생성자 - JavaScript | MDN

Array() 생성자는 새로운 Array 객체를 생성할 때 사용합니다.

developer.mozilla.org

 

📌 of( )

Array.of()는 new Array()와 다르게 숫자를 전달해도 배열 요소로 저장된다.

매개변수 없이 Array.of()만 사용하면 빈 배열이 생성된다. (new Array()와 동일한 결과)

Array.of(요소들...)
const arr1 = Array.of(5);  
console.log(arr1); // [5] (배열 길이가 아닌 요소)

const arr2 = Array.of(1, 2, 3);
console.log(arr2); // [1, 2, 3]

console.log(new Array(3));   // [ <3 empty items> ]
console.log(Array.of(3));    // [3]

 

Array.of(n)은 길이가 n인 배열이 아니라, 하나의 요소가 n인 배열이다.

 

다차원 배열에서도 사용할 수 있다.

const matrix = Array.of([1, 2, 3], [4, 5, 6], [7, 8, 9]);
console.log(matrix);
/*
[
  [1, 2, 3], 
  [4, 5, 6], 
  [7, 8, 9]
]
*/

 

⏳ 시간 복잡도 O(N)이다.

 

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

 

Array.of() - JavaScript | MDN

array.of() 정적 메서드는 인자의 수나 유형에 관계없이 가변적인 수의 인자로부터 새로운 Array 인스턴스를 생성합니다.

developer.mozilla.org

 

📌 from( )

Array.from()은 유사 배열 또는 이터러블 객체를 배열로 변환할 때 사용한다.

Array.from(유사배열객체, 함수?, thisArg?)

 

배열의 모든 요소에 대해 호출할 함수를 넘겨줄 수 있다.

단, Array.from()은 반드시 매개변수를 필요로하기 때문에 매개변수 없이 Array.from()으로만 호출하면 TypeError가 발생한다.

하지만 Array.from({ length: 0 })를 호출하면 빈 배열을 반환한다.

const arr1 = Array.from("hello");  
console.log(arr1); // ['h', 'e', 'l', 'l', 'o']

const arr2 = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(arr2); // [1, 2, 3, 4, 5]

 

⏳ 시간 복잡도 O(N)이다.

 

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

 

Array.from() - JavaScript | MDN

Array.from() 정적 메서드는 순회 가능 또는 유사 배열 객체에서 얕게 복사된 새로운 Array 인스턴스를 생성합니다.

developer.mozilla.org

 

📌 fill( )

 배열의 인덱스 범위 내에 있는 모든 요소를 정적 값으로 변경한 후, 그렇게 수정된 배열을 반환한다.

배열.fill(변경할값, startIndex?, endIndex?)
const arr1 = new Array(5).fill(0);
console.log(arr1); // [0, 0, 0, 0, 0]

const arr2 = [1, 2, 3, 4, 5];
arr2.fill(9, 1, 3);  // 인덱스 1~2만 9로 채우기
console.log(arr2); // [1, 9, 9, 4, 5]

 

매개변수 없이 배열.fill()로만 호출하면 undefined로 채워진다.

이미 존재하는 배열에 사용하면 요소들이 변경된다.

const arr1 = new Array(3).fill()
console.log(arr1)  // [undefined, undefined, undefined]

const arr2 = [0, 0, 0].fill()
console.log(arr2)  // [undefined, undefined, undefined]

 

주의할 점은, fill()은 배열과 같은 객체를 채우면 모든 요소가 같은 객체를 참조한다.

요소가 객체인 배열을 만들거나 2차원 배열을 만들 때 주의해야한다.

let arr = new Array(3).fill({});
arr[0].name = "Alice";
console.log(arr); // ❌ [{name: "Alice"}, {name: "Alice"}, {name: "Alice"}] (모두 같은 객체)

 

이럴 때는 독립된 객체가 생성되도록 map이나 from에서 함수로 넘겨주면 된다.

const arr = Array.from({ length: 3 }, () => ({}));
arr[0].name = "Alice";
console.log(arr); // [{name: "Alice"}, {}, {}] (독립된 객체)

 

⏳ 시간 복잡도 O(N)이다.

 

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

 

Array.prototype.fill() - JavaScript | MDN

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

developer.mozilla.org

 

📌 with( )

ES2023(ES14)에서 새롭게 추가된 문법으로, 기존 배열을 변경하지 않고 특정 요소를 수정하여 새로운 배열을 반환한다. (Immutable)

배열.with(변경할index, newValue)
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 99); // 인덱스 2의 값을 99로 변경

console.log(arr);   // [1, 2, 3, 4, 5] (원본 유지)
console.log(newArr); // [1, 2, 99, 4, 5] (새로운 배열)

 

음수 인덱스도 가능하다.

const arr = ["a", "b", "c", "d"];
const newArr = arr.with(-1, "z");  // 마지막 요소 변경
console.log(newArr); // ["a", "b", "c", "z"]

 

하지만, 존재하지 않는 인덱스를 변경하려 하면 RangeError가 발생한다.

매개변수 없이 배열.with()로만 호출하게 되면 첫 번째 요소가 undefined로 변경된다.

console.log([1, 2, 3].with());  
// [undefined, 2, 3] (첫 번째 요소가 `undefined`로 변경됨)

 

다차원 배열에서도 사용할 수 있다.

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

const newMatrix = matrix.with(0, [9, 9]);  // 첫 번째 행을 변경
console.log(newMatrix); // [[9, 9], [3, 4]]
console.log(matrix); // [[1, 2], [3, 4]] (원본 유지)

 

⏳ 시간 복잡도 O(N)이다.

 

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

 

Array.prototype.with() - JavaScript | MDN

Array 인스턴스의 with() 메서드는 주어진 인덱스의 값을 변경하기 위해 대괄호 표기법을 사용하는 것의 복사 버전입니다. 이 함수는 지정된 인덱스의 요소가 지정된 값으로 대체된 새 배열을 반환

developer.mozilla.org

 

📌 copyWithin( )

기존 배열의 일부를 복사하여 같은 배열 내에서 다른 위치에 덮어쓰기해준다.

배열.copyWithin(덮어쓸startIndex, 복사할startIndex, 복사할endIndex?)
/* 배열의 일부를 다른 위치로 복사 */
const arr1 = [1, 2, 3, 4, 5];
arr1.copyWithin(0, 3); // 인덱스 3부터 시작하는 요소를 인덱스 0부터 덮어쓰기
console.log(arr1); // [4, 5, 3, 4, 5]

/* 특정 부분만 복사 */
const arr2 = [10, 20, 30, 40, 50, 60];
arr2.copyWithin(1, 3, 5);  // 인덱스 3~4 요소를 인덱스 1부터 덮어쓰기
console.log(arr); // [10, 40, 50, 40, 50, 60]

 

주의할 점은, 배열 길이를 늘리거나 줄이지 않고(배열의 길이는 유지) 기존 배열을 덮어쓰기 하기 때문에 새로운 배열을 반환하지 않고 원본을 변경한다. (mutable)

원본을 유지하려면 slice나 spread 연산자를 사용해야한다.

매개변수 없이 호출하면 에러 없이 기존 배열을 반환한다.

const arr = [1, 2, 3, 4, 5];
const newArr = [...arr].copyWithin(2, 0, 2);
console.log(newArr); // [1, 2, 1, 2, 5] (원본 유지)

 

복사할 start와 end 모두 생략하고 덮어쓸 index만 써도 에러는 발생하지 않는다.

// copyWithin(2, 0, array.length)와 동일함
console.log([1, 2, 3, 4, 5].copyWithin(2)); // [1, 2, 1, 2, 3]

 

즉, 배열의 처음부터(0) 배열 끝까지(length) 복사한 후, target 위치(2)부터 덮어쓰기 한다.

 

다차원 배열에서도 사용할 수 있다. 행 단위로 복사가 가능하다.

const matrix = [
  [1, 2, 3], 
  [4, 5, 6], 
  [7, 8, 9]
];

matrix.copyWithin(0, 1);  // 1번 행을 0번 행으로 복사
console.log(matrix);
/*
[
  [4, 5, 6], 
  [4, 5, 6], 
  [7, 8, 9]
]
*/

 

⏳ 시간 복잡도 O(N)이다.

 

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

 

Array.prototype.copyWithin() - JavaScript | MDN

Array 인스턴스의 copyWithin() 메서드는 배열의 일부를 같은 배열의 다른 위치로 얕게 복사하며, 배열의 길이를 수정하지 않고 해당 배열을 반환합니다.

developer.mozilla.org