Ryu.log

Array.from() 본문

Prev-content

Array.from()

류뚝딱 2018. 11. 5. 12:01

Array.from()

Array.from() 메소드는 배열로 변환할 유사 배열 혹은 반복 가능한 객체를 이용하여, 복사된 배열을 리턴 해준다.

console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"] 
console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]
Array.from(Array, MapFn(thisArg)); 
// Array : 배열로 변환할 유사배열 또는 반복가능한 객체 
// MapFn : 모든 배열요소에서 호출할 Map 함수 
// thisArg : Map함수 내에 item으로 사용될 값

예제 코드

String에서 배열만들기

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

Set에서 배열만들기

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

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'];

배열형태를 가진 객체(arguments)에서 배열만들기

function f() { return Array.from(arguments); } f(1, 2, 3); // [1, 2, 3]

Array.from과 Arrow함수 사용하기

Array.from([1, 2, 3], x => x + x); // [2, 4, 6] 
Array.from(, (v, i) => i); // [0, 1, 2, 3, 4]

Comments