[Javascript] Array.from()을 이용한 배열 초기화

Chaedie·2022년 6월 18일
0

Javascript

목록 보기
5/8
post-thumbnail

출처 MDN

// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]

// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

Array.from()을 사용하면 배열을 초기화 할 때 특정 값으로 초기화가 가능해진다.
(비슷한 함수로는 Array.fill())


numbers = {
  all: [],
  addAll(max_num) {
    this.all = Array
      .from(new Array(max_num - 1), (v, i) => i + 2);
  },
};
numbers.addAll(10);
// [2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.from()으로 만들고자 했던건 2부터 원하는 값까지 의 배열
(파이썬의 Range()함수와 같은 기능)

profile
TIL Blog - Today's Intensive Learning!

0개의 댓글