IT/JavaScript
[JS] Array.from()이란? 쪼개서 배열로 만들고 싶을 때 ! 👌
스콘_
2021. 10. 28. 09:24
반응형
Array.from() 메서드는 유사 배열 객체(arrat-like object)나 반복 가능한 객체(literable object)를 얕게 복사해 새로운 Array 객체를 만듭니다.
동물원이라는 String객체를 쪼갤 수 있습니다.
데이터를 조작하다보면 기존 객체를 이용해 새로운 배열을 만들어야 할 때가 있는데요. 그러할 때 유용한 메서드 입니다.
1. String에서 배열 만들기.
Array.from('동물원');
// ["동", "물", "원"]
2. Set에서 배열 만들기
const s = new Set(['foo', window]);
Array.from(s);
// ["foo", window]
3. Map에서 배열 만들기
const m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
4. Array.from과 화살표 함수 사용하기
// 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]
거의 모든 웹브라우저와 호환이 되지만, IE는 되지 않습니다.