๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป Array.from()

whenยท2022๋…„ 7์›” 14์ผ

์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด(array-like object)๋‚˜ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด(iterable object)๋ฅผ ์–•๊ฒŒ ๋ณต์‚ฌํ•ด ์ƒˆ๋กœ์šด Array ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค.

Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike : ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ณ ์ž ํ•˜๋Š” ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด๋‚˜ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด
mapFn : ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ์— ๋Œ€ํ•ด ํ˜ธ์ถœํ•  ๋งตํ•‘ ํ•จ์ˆ˜
thisArg : mapFn ์‹คํ–‰ ์‹œ์— this๋กœ ์‚ฌ์šฉํ•  ๊ฐ’

๋ฐ˜ํ™˜๊ฐ’ : ์ƒˆ๋กœ์šด Array ์ธ์Šคํ„ด์Šค

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ์— Array.from()์œผ๋กœ ์ƒˆArray๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

  • ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด(length ์†์„ฑ๊ณผ ์ธ๋ฑ์‹ฑ๋œ ์š”์†Œ๋ฅผ ๊ฐ€์ง„ ๊ฐ์ฒด)
  • ์ˆœํšŒ ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด(Map, Set ๋“ฑ ๊ฐ์ฒด์˜ ์š”์†Œ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ๊ฐ์ฒด)

๐ŸŒˆ ์˜ˆ์ œ

  • 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๊ณผ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ์‚ฌ์šฉํ•˜๊ธฐ
// 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]
  • ์‹œํ€€์Šค ์ƒ์„ฑ๊ธฐ(range)
// 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

profile
์ƒ์ƒ์€ ํ˜„์‹ค์ด ๋œ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€