Study/JavaScript

Array.from()

더 멋진 세상을 꿈꾸는 개발자 2020. 6. 13. 13:06

 

 

Array.from() 메서드는 유사 배열 객체(array-like object)나반복 가능한 객체(iterable object)를 얕게 복사해

새로운Array 객체를 만든다.

 

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(arrayLike[, mapFn[, thisArg]])

 

 

매개변수

 

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

 

 

반환 값

  새로운 array 인스턴스

 

 

 

 

예제


1. string에서 배열만들기

 

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

 

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. 배열 형태를 가진 객체(arguments)에서 배열 만들기

function f() {
  return Array.from(arguments);
}

f(1, 2, 3);

// [1, 2, 3]

 

 

5. 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]

 

 

 

 

출처 : mdn