array.from

Tags
변환
새로운 배열 생성
요약
배열을 생성과 동시에 초기화 하기에도 좋음 유사배열을 배열로 만들거나, 시퀀스 배열 만들 때 좋음. - Array.from('foo'); // ["f", "o", "o"] - [0,1,2,3,4], [0,2,4,6,8]과 같은 시퀀스 배열 생성
 
 
Array.from(arrayLike[, mapFn[, thisArg]])
  • 유사 배열 객체(array-like object)
  • 반복 가능한 객체(iterable object)
얕게 복사새로운 Array 객체 생성.
 

매개변수

1) arrayLike Required 배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.
2) mapFn Optional 배열의 모든 요소에 대해 호출할 맵핑 함수.
3) thisArgOptional mapFn 실행 시에 this로 사용할 값.

반환값

새로운 Array 인스턴스.
 

사용 예시

string에서 배열로 만들기

Array.from('foo'); // ["f", "o", "o"]

Set 에서 배열 만들기

const s = new Set(['foo', window]); Array.from(s); // ["foo", window]

시퀀스 배열 생성 (화살표 함수로 조건 명시)

const arr = Array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4] Array.from([1, 2, 3], x => x + x); // [2, 4, 6]

시퀀스 생성기 (원하는 대로 인자 받아서 만들기)

// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc) const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); // Generate numbers range 0..4 range(0, 4, 1); // [0, 1, 2, 3, 4] // Generate numbers range 1..10 with step of 2 range(1, 10, 2); // [1, 3, 5, 7, 9] // Generate the alphabet using Array.from making use of it being ordered as a sequence range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x)); // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

배열 크기, 값, 인덱스를 이용하여 원하는 대로 할당하기

const test = Array.from({length:8}, (value, index)=>({amount: 0, position:index})) (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {amount: 0, position: 0} 1: {amount: 0, position: 1} 2: {amount: 0, position: 2} 3: {amount: 0, position: 3} 4: {amount: 0, position: 4} 5: {amount: 0, position: 5} 6: {amount: 0, position: 6} 7: {amount: 0, position: 7} length: 8 [[Prototype]]: Array(0)