๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŒŒ | WEB DEV/Vanilla JS

JS_๋ฌธ๋ฒ• (2)_๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น2, Rest-Spread ํŒŒ๋ผ๋ฏธํ„ฐ

by KASSID 2022. 2. 15.

๋ชฉ์ฐจ

    728x90

    ๋ณ€์ˆ˜ ๊ฐ’ ๊ตํ™˜ํ•˜๊ธฐ

    let a = 1;
    let b = 2;
    [a, b] = [b, a] //๋Œ€๊ด„ํ˜ธ๋กœ ํ•ด์•ผ ๊ฐ€๋Šฅ
    console.log(a, b)
    
    >>>
    2 1

    ๋‹ค๋ฅธ ์–ธ์–ด์— ๋น„ํ•ด์„œ

    ๊ตํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ฐ„๊ฒฐํ•˜๋‹ค.

     

    ํ•œ ๋ฒˆ์— ์—ฌ๋Ÿฌ ๊ฐ’ ํ• ๋‹น

    let a = 1;
    let b = 2;
    [a, b] = [3, 4]
    
    console.log(a, b)
    
    >>>
    3 4

    ํŒŒ์ด์ฌ์˜ ํŠœํ”Œ์ฒ˜๋Ÿผ ์—ฌ๋Ÿฌ ๊ฐ’์„ ํ• ๋‹นํ•˜๋Š” ๊ฒƒ์€

    ์œ„์ฒ˜๋Ÿผ ์จ์ฃผ๋ฉด ๊ฐ€๋Šฅํ•˜๋‹ค.

     

    function data(){
        return [1, 2]
    }
    let [a,b] = data()
    console.log(a, b)
    
    >>>
    1 2

    ํ•จ์ˆ˜์˜ ๋ฆฌํ„ด๊ฐ’์„ ๋ฐฐ์—ด๋กœ ์ง€์ •ํ•˜๋Š” ๊ฒƒ๋„

    ์—ฌ๋Ÿฌ ๊ฐ’์„ ํ• ๋‹น์‹œํ‚ค๋Š” ๋ฐ์— ์ด์šฉ๊ฐ€๋Šฅํ•˜๋‹ค.

     

    ๋ฌธ์ž์—ด ๋ถ„๋ฆฌ

    ํŒŒ์ด์ฌ์—๋„ ์žˆ๋Š” .split() ํ•จ์ˆ˜!

    let data = 'Hello my name is Kassid'
    console.log(data.split(' '))
    
    >>>
    [ 'Hello', 'my', 'name', 'is', 'Kassid' ]

    ์ง€์ •ํ•œ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋ถ„๋ฆฌํ•˜๊ณ 

    ๋ฐฐ์—ด์— ๋‹ด์•„์„œ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

     

    let data = 'one,two,three,four'
    let [n1,n2,n3,n4]=data.split(',')
    console.log(n1, n2, n3, n4)
    
    >>>
    one two three four

    ์œ„์™€ ๊ฐ™์ด ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น์—๋„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

     

    Rest ํŒŒ๋ผ๋ฏธํ„ฐ

    ... ์„ ํ•จ์ˆ˜์˜ ์ธ์ž์— ๋ถ™์—ฌ์ฃผ๋Š” ๊ฒƒ์ด๋‹ค.

    (ํŒŒ์ด์ฌ์˜ *args์™€ ๊ฐ™์€ ๊ฐœ๋…)

    function data(...items) {
        console.log(items)
    }
    
    data(1,2,3,4,5)
    
    >>>
    [ 1, 2, 3, 4, 5 ]

    ์ฃผ์˜ํ•  ์ ์€

    ์—ญ์‹œ๋‚˜ rest ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” ๋’ค์— ๋†“์•„์•ผ

    ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.

     

    Spread ํŒŒ๋ผ๋ฏธํ„ฐ

    ๋ฐฐ์—ด, ๋ฌธ์ž์—ด ๋“ฑ  iterable ๋ณ€์ˆ˜ ์•ž์— ๋ถ™์—ฌ์„œ

    ๊ฐœ๋ณ„ ์•„์ดํ…œ์œผ๋กœ ๋ถ„๋ฆฌ ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

    (iterable : ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด)

     

    const data = [1,2,3,4,5]
    console.log(...data)
    
    >>>
    1 2 3 4 5

    ์œ„์ฒ˜๋Ÿผ ์•„์ดํ…œ์„ ํ•˜๋‚˜์”ฉ ๋ถ„๋ฆฌํ•ด์„œ ์ถœ๋ ฅํ•ด์ค€๋‹ค.

     

    SpreadํŒŒ๋ผ๋ฏธํ„ฐ๋Š” ํ•จ์ˆ˜์˜ ์ธ์ž ์ˆ˜์— ๋งž์ถฐ์„œ

    ํ•˜๋‚˜์”ฉ ๋ฐฐ์—ด์˜ ์•„์ดํ…œ์„ ๋Œ€์ž…ํ•ด์ฃผ๊ณ  ์‹ถ์„ ๋•Œ

    ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

    function func(a,b,c) {
        console.log(a)
        console.log(b)
        console.log(c)
    }
    const data = [1,2,3,4,5]
    func(...data)
    
    >>>
    1
    2
    3
    4
    5

     

    ๊ธฐ์กด ๋ฐฐ์—ด์„ ์ด์šฉํ•ด

    ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๊ตฌ์„ฑํ•  ๋•Œ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

    const arr1 = [1,2,3]
    const arr2 = [0,...arr1, 4,5,6]
    console.log(arr2)
    
    >>>
    [ 0, 1, 2, 3, 4, 5, 6 ]

    ์ด์ „์— ๋‹ค๋ค˜๋˜

    concat๊ณผ ๋‹ค๋ฅธ ์ ์€

    ๋ฐฐ์—ด์„ ๋„ฃ์„ ๋•Œ ์œ„์น˜๋ฅผ ์ •ํ•ด์ค„ ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด๋‹ค.

    (๋ฌธ์ž์—ด formatingํ•˜๋Š” ๋Š๋‚Œ)

    ๋Œ“๊ธ€