Javascript 배열(1차원/2차원) 초기화 하기
1. 1차원 배열
1. Array() 생성자
Array() 생성자는 Array 객체를 생성한다.
new Array(element1, element2, ...elementN) // [element1, element2, ... elementN]
new Array(ArrayLength) // [undefined, ...] ArrayLength만큼
2. Array.prototype.fill()
fill() 메서드는 배열의 시작 인덱스 부터 끝 인덱스의 이전까지 정적인 값 하나로 채운다.
arr.fill(value[, start[, end]])
value: 배열을 채울 값
start: 시작 인덱스. 기본값은 0
end: 끝 인덱스. 기본값은 this.length
const arr = [1,2,3,4]
console.log(arr.fill(0,2,4)) // [1, 2, 0, 0]
console.log(arr.fill(0,5)) // [1, 5, 5, 5]
console.log(arr.fill(6)) // [6, 6, 6, 6]
3. fill() Example
// 길이가 3이고 값이 0인 배열
console.log(new Array(5).fill(0)) // [0, 0, 0]
// 길이가 5인 배열에 값이 true인배열
console.log(new Array(5).fill(true) // [true, true, true, true, true]
4. Array.from()
Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 만든다.
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike: 배열을 변환하고자 하는 유사 배열 객체나 반복 가능한 객체
start: 배열의 모든 요소에 대해 호출할 맵핑 함수
end: mapFn 실행 시에 this로 사용할 값
5. from() Example
// 길이가 5이고 값이 0인 배열
console.log(Array.from({length: 5}, ()=>0)) //[0,0,0,0,0]
// 길이가 5이고 값이 1부터 5까지인 배열
console.log(Array.from({length: 5}, (v, index)=> index)) // [1,2,3,4,5]
2. 2차원 배열
// arr[5][2] (빈 배열 생성)
const arr1 = Array.from(Array(5), () => new Array(2)
// arr[5][4] (3으로 초기화하여 생성)
const arr2 = Array.from(Array(5), () => Array(4).fill(3))
// arr[col][row] 1씩 증가하는 배열
const arr1 = Array.from({ length: col }, (v, r)
=> { return Array.from({ length: row }, (v, c)
=> (r * 5) + (c + 1)) }); // 1번째 방법
const arr2 = [...Array(row)].map((v, r)
=>[...Array(col)].map((v, c)
=>(r * col) + (c + 1))); // 2번째 방법
2번째 방법이 가독성이 더 좋아 2번째 방법을 추천한다.
참조: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Array