์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด(array-like object)๋ ๋ฐ๋ณต ๊ฐ๋ฅํ ๊ฐ์ฒด(iterable object)๋ฅผ ์๊ฒ ๋ณต์ฌํด ์๋ก์ด Array ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค.
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike : ๋ฐฐ์ด๋ก ๋ณํํ๊ณ ์ ํ๋ ์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด๋ ๋ฐ๋ณต ๊ฐ๋ฅํ ๊ฐ์ฒด
mapFn : ๋ฐฐ์ด์ ๋ชจ๋ ์์์ ๋ํด ํธ์ถํ ๋งตํ ํจ์
thisArg : mapFn ์คํ ์์ this๋ก ์ฌ์ฉํ ๊ฐ
๋ฐํ๊ฐ : ์๋ก์ด Array ์ธ์คํด์ค
๋ค์๊ณผ ๊ฐ์ ๊ฒฝ์ฐ์ Array.from()์ผ๋ก ์Array๋ฅผ ๋ง๋ค ์ ์๋ค.
๐ ์์
Array.from('foo');
// ["f", "o", "o"]
const s = new Set(['foo', window]);
Array.from(s);
// ["foo", window]
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'];
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [1, 2, 3]
// 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});
// [undefined, undefined, undefined, undefined, undefined]
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
Array.from({length: 5}, (v, i) => i+1);
// [1, 2, 3, 4, 5]
// 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"]
๐ญ ์ถ์ฒ
MDN
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from