Javascript, fill()과 map()으로 1부터 100까지 배열 생성하기

MinJae·2021년 5월 3일
7

제로초님 자바스크립트 유툽 실시간 방송을 보다가

유용할 것 같아서 따로 블로그에 정리!😗


10 * 10 배열 && 각 자리 값이 0 ~ 99

  1. 빈 배열 생성
const h = 10;
const w = 10;

const grid = Array(h * w)

console.log(grid);


[ <100 empty items> ] //결과

  1. fill()로 각 자리를 채우기
const h = 10;
const w = 10;

const grid = Array(h * w).fill() //fill 인자가 없으므로 undefine 할당됨

console.log(grid);


[
  undefined, undefined, undefined, undefined, undefined, undefined,
  undefined, undefined, undefined, undefined, undefined, undefined,
  undefined, undefined, undefined, undefined, undefined, undefined,
  undefined, undefined, undefined, undefined, undefined, undefined,
  undefined, undefined, undefined, undefined, undefined, undefined,...]

  1. map()으로 각 자리 index에 해당하는 값 할당하기
const h = 10;
const w = 10;

const grid = Array(h * w).fill().map((arr, i) => {  // (arr: 현재값, i:인덱스)
    return i
})

//Array(h * w).fill()의 각 값(undefined)을 map()을 통해 하나씩 불러와서 i로 return
//map()은 각각 return한 값으로 이루어진 배열을 생성함
//생성된 배열이 grid가 됨!!

console.log(grid);


[
   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,
  12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
  24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, ... 99]

다음 포스팅은 fill()을 사용하여 2차원 배열을 생성 했을 때

값들이 다 같이 변하는 현상으로 코테 때 뚝배기가 터졌던 건에 대해 포스팅 하겠읍니다...

profile
나 개발 좋아하네?

1개의 댓글

comment-user-thumbnail
2021년 5월 5일

첫 댓글러 등장! 😎

답글 달기