배열 내부에 원하는 값을 삽입하기 위해 javascript 특정 길이의 배열을 생성해야 했다. 여러가지 방법으로 배열 사이즈를 생성할 수 있는데, 그 방법에 대해 알아보자. 👻
특정 길이의 빈 배열을 만드는 첫 번째 방법은 Array() 생성자를 사용하고 정수를 인수로 전달하는 것이다. 생성자를 호출하기 때문에 new 키워드를 사용한다.
Input :
var arr = new Array(5);
console.log(arr)
Output :
[undefined, undefined, undefined, undefined, undefined]
apply() 메소드를 사용하여 배열 형태로 메소드에 파라미터를 넣을 수 있다. apply() 메소드는 2개의 파라미터를 취한다. 첫 번째는 this 인수에 대한 참조이고 두 번째는 배열이다.
Input :
var myArr = Array.apply(null, Array(5));
console.log(myArr);
Onput :
[undefined, undefined, undefined, undefined, undefined]
Input :
[...Array(5)].map(x => 0);
Onput :
[0, 0, 0, 0, 0]
Input :
Array(5).fill(0);
Onput :
[0, 0, 0, 0, 0]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array