๋ฐ˜์‘ํ˜•

Array.fill() ๋ฉ”์„œ๋“œ๋Š” ์ด๋ฆ„ ๊ทธ๋Œ€๋กœ ์ฒซ ๋ฒˆ์งธ ์ธ์ž์— ์ฃผ์–ด์ง„ ๊ฐ’์œผ๋กœ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ์ฑ„์šฐ๋Š” ๋ฉ”์„œ๋“œ๋‹ค. ์ฃผ๋กœ Array() ์ƒ์„ฑ์ž์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜์—ฌ, ์ดˆ๊ธฐ๊ฐ’์ด ํ• ๋‹น๋œ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•  ๋•Œ ์œ ์šฉํ•˜๊ฒŒ ์“ฐ์ธ๋‹ค.

Array.fill(value, start?, end?)

// length๊ฐ€ 2์ธ ๋นˆ ๋ฐฐ์—ด ์ƒ์„ฑ ํ›„ null๋กœ ์ฑ„์›€
const filledArray = Array(2).fill(null);
console.log(filledArray); // [null, null]

const numbers = [1, 2, 3, 4];
// 2~3๋ฒˆ ์ธ๋ฑ์Šค๋ฅผ null๋กœ ์ฑ„์›€ (start ํฌํ•จ, end ๋ฏธํฌํ•จ)
numbers.fill(null, 2, 4);
console.log(numbers); // [1, 2, null, null]

 

์ด๋•Œ ์ฃผ์˜ํ•  ์ ์€, ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋Š” fill(value) ๋ฉ”์„œ๋“œ ์ฒซ ๋ฒˆ์งธ ์ธ์ž๋กœ ์ „๋‹ฌํ•œ value ๊ฐ’์„ ๊ฐ€๋ฆฌํ‚จ ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๋งŒ์•ฝ value๊ฐ€ ๊ฐ์ฒด๋ผ๋ฉด ๋ชจ๋“  ์š”์†Œ๋Š” ๋™์ผํ•œ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•˜๊ฒŒ ๋œ๋‹ค.

const arr = Array(2).fill({ name: "John" });
console.log(arr); // [{ name: 'John' }, { name: 'John' }]
console.log(arr[0] === arr[1]); // true

 

ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ๊ฐ’์„ ์ƒ์„ฑํ•˜๊ณ  fill() ์ธ์ž๋กœ ๋„˜๊ฒจ๋„ ๊ฒฐ๊ณผ์ ์œผ๋กœ ๋ฐฐ์—ด ๋‚ด ๋ชจ๋“  ์š”์†Œ๋Š” ๋™์ผํ•œ ์ฐธ์กฐ ๊ฐ’์„ ๊ณต์œ ํ•œ๋‹ค. ์•„๋ž˜ ์˜ˆ์ œ์˜ getUser() ํ•จ์ˆ˜๋Š” ํ˜ธ์ถœ๋  ๋•Œ๋งˆ๋‹ค ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฐ˜ํ™˜ํ•˜์ง€๋งŒ, fill() ์ธ์ž์—์„œ ์‚ฌ์šฉํ•˜๋ฉด ๋‹จ ํ•œ ๋ฒˆ๋งŒ ํ˜ธ์ถœ๋˜๋ฉฐ, ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋Š” ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ์— ํ• ๋‹น๋œ๋‹ค.

const getUser = (name = "John") => {
  console.count("getUser"); // getUser: 1 (1ํšŒ ํ˜ธ์ถœ)
  return { name };
};

const arr = Array(2).fill(getUser()); 
console.log(arr); // [{ name: 'John' }, { name: 'John' }]
console.log(arr[0] === arr[1]); // true

 

๊ฐ ์š”์†Œ๊ฐ€ ๋…๋ฆฝ์ ์ธ ๊ฐ์ฒด๋ฅผ ๊ฐ€์ ธ์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ fill() ๋ฉ”์„œ๋“œ ๋ณด๋‹จ, Array.from() ์ •์  ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋” ์ ์ ˆํ•˜๋‹ค. Array.from() ๋ฉ”์„œ๋“œ๋Š” ์œ ์‚ฌ๋ฐฐ์—ด ํ˜น์€ ์ดํ„ฐ๋Ÿฌ๋ธ”์„ ๋ฐ›์•„ ์–•์€ ๋ณต์‚ฌ ํ›„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜๋Š”๋ฐ, ๋‘ ๋ฒˆ์งธ ์ธ์ž๋กœ ๋งคํ•‘ ํ•จ์ˆ˜๋ฅผ ๋„˜๊ธธ ์ˆ˜ ์žˆ๋‹ค.

Array.from(arrayLike, mapFn(element, index)?)

const getUser = (name = "John") => {
  console.count("getUser"); // getUser: 2 (2ํšŒ ํ˜ธ์ถœ)
  return { name };
};

// length๊ฐ€ 2์ธ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜๊ณ  ๊ฐ ์š”์†Œ์— getUser ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๊ฐ์ฒด ์ƒ์„ฑ
const arr = Array.from({ length: 2 }, getUser);
console.log(arr); // [{ name: 'John' }, { name: 'John' }]
console.log(arr[0] === arr[1]); // false

 


๊ธ€ ์ˆ˜์ •์‚ฌํ•ญ์€ ๋…ธ์…˜ ํŽ˜์ด์ง€์— ๊ฐ€์žฅ ๋น ๋ฅด๊ฒŒ ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค. ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”
๋ฐ˜์‘ํ˜•