๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
[๊ฐœ๋ฐœ] Practice/JavaScript ES6

[JavaScript / ES6] Spread Operator

by Connecting-the-dots 2022. 4. 21.
728x90
๋ฐ˜์‘ํ˜•

๐Ÿ’ก ์‹ค์Šต ํฌ์ธํŠธ!

๐Ÿ’œ Spread Operator

  • ์—ฐ๋‹ฌ์•„์„œ ๋งˆ์นจํ‘œ๋ฅผ 3๊ฐœ ์ฐ์œผ๋ฉด ๊ทธ๊ฒƒ์ด spread operator!
  • spread operator ๋Š” ํ•ญ์ƒ ๋Œ€๊ด„ํ˜ธ ์•ˆ, ์ค‘๊ด„ํ˜ธ ์•ˆ, ํ•จ์ˆ˜ ์•ˆ์˜ ์†Œ๊ด„ํ˜ธ์—์„œ๋งŒ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅ

๐Ÿ’œ Spread Operator ์˜ ์—ญํ•  ์•Œ์•„๋ณด๊ธฐ

๐Ÿค Array ์— ๋ถ™์ด๋ฉด ๋Œ€๊ด„ํ˜ธ ์ œ๊ฑฐ

let arr = ["hello", "world"];

console.log(arr); // ['hello', 'world']

console.log(...arr); // hello world
console.log("hello", "world"); // hello world

๐Ÿค String ์— ๋ถ™์ด๋ฉด String ์„ ํ•˜๋‚˜์”ฉ ๋ถ„๋ฆฌ

let str = "hello";

console.log(str); // hello

console.log(...str); // h e l l o
console.log("h", "e", "l", "l", "o"); // h e l l o

๐Ÿ’œ Spread Operator ์˜ ํ™œ์šฉ ์•Œ์•„๋ณด๊ธฐ

๐Ÿค ๋‘ ๊ฐœ ์ด์ƒ์˜ Array ๋ฅผ ํ•ฉ์น˜๊ฑฐ๋‚˜ ๋ณต์‚ฌํ•  ๋•Œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

let a = [1, 2, 3];
let b = [4, 5];

let c = [...a];
let d = [...a, ...b];

console.log(c); // [1, 2, 3]
console.log(d); // [1, 2, 3, 4, 5]

let e = [1, 3, 5];
let f = e; // ๊ทธ๋ƒฅ ๋“ฑํ˜ธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ณต์‚ฌํ•˜๋ฉด ๊ฐ’์„ ๊ณต์œ (shallow copy)

e[3] = 7;

console.log(e); // [1, 3, 5, 7]
console.log(f); // [1, 3, 5, 7]

let g = [2, 4, 6];
let h = [...g]; // spread operator ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ณต์‚ฌํ•˜๋ฉด ๋…๋ฆฝ์ ์ธ ๊ฐ’์„ ๊ฐ€์ง(deep copy)

g[3] = 8;

console.log(g); // [2, 4, 6, 8]
console.log(h); // [2, 4, 6]

๐Ÿค ๋‘ ๊ฐœ ์ด์ƒ์˜ Object ๋ฅผ ํ•ฉ์น˜๊ฑฐ๋‚˜ ๋ณต์‚ฌํ•  ๋•Œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

// copy ํ•˜๋‹ค๊ฐ€ ๊ฐ‘ ์ค‘๋ณต์ด ๋ฐœ์ƒํ•˜๋ฉด ๊ฐ€์žฅ ๋’ค์— ์œ„์น˜ํ•˜๋Š” ๊ฐ’์„ ์ ์šฉ

let o1 = { a: 1, b: 2 };
let o2 = { ...o1, c: 3 };
let o3 = { ...o1 };
let o4 = { ...o1, a: 2 };
let o5 = { a: 2, ...o1 };

console.log(o2); // {a: 1, b: 2, c: 3}
console.log(o3); // {a: 1, b: 2}
console.log(o4); // {a: 2, b: 2}
console.log(o5); // {a: 1, b: 2}

๐Ÿค ํ•จ์ˆ˜์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋„ฃ์„ ๋•Œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

function add(a, b, c) {
    console.log(a + b + c);
}

add(1, 2, 3); // 6

let nums = [10, 20, 30];

add(nums[0], nums[1], nums[2]); // 60 => ์ฃผ๋จน๊ตฌ๊ตฌ์‹
add.apply(undefined, nums); // 60 => ์˜›๋‚ ๋ฐฉ์‹
add(...nums); // 60 => ์š”์ฆ˜๋ฐฉ์‹

๐Ÿ“Œ apply() ์™€ call()

let person = {
    hello: function () {
        console.log(this.name + " hello");
    },
    age: function (age) {
        console.log(this.name + " " + age);
    },
};

let person2 = {
    name: "Seoyun",
};

person.hello(); // undefined hello

// person2 ์— person.hello() ๋ฅผ ์ ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ apply(), call() ์‚ฌ์šฉ ๊ฐ€๋Šฅ!
person.hello.apply(person2); // Seoyun hello
person.hello.call(person2); // Seoyun hello

// person2 ์— person.age() ๋ฅผ ์ ์šฉํ•  ๋•Œ apply(), call()์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋„ฃ๋Š” ๋ฐฉ๋ฒ•์ด ๋‹ค๋ฆ„!
person.age.apply(person2, [30]); // Seoyun 30
person.age.call(person2, 30); // Seoyun 30

 

728x90
๋ฐ˜์‘ํ˜•