[JS] 2차원 배열 만들기

KJA·2022년 11월 3일
0

for 문

const arr = [];
for (let i = 0; i < 3; i++) {
  // 세로
  const cells = [];
  for (let j = 0; j < 6; j++) {
    // 가로
    cells.push(0);
  }
  arr.push(cells);
}

console.log(arr);

/* 결과
[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]
*/

Array.from()

const n = 3;
const m = 6;
const arr = Array.from(Array(n), () => new Array(m).fill(0));

console.log(arr);

/* 결과
[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]
*/

Array.prototype.map()

const n = 3;
const m = 6;
const arr = Array(n).fill().map(() => Array(m).fill(0));

console.log(arr);

/* 결과
[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]
*/

0개의 댓글