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

JS_๊ธฐ๋ณธ ๋ฌธ๋ฒ• (29)_ Tagged Literals

by KASSID 2023. 8. 5.

๋ชฉ์ฐจ

    728x90

    ES6๋ถ€ํ„ฐ๋Š” Tagged Literals ๋ผ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค. ์ด์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด์ž.

     

    1. Tagged Literals

    Tagged Literals๋Š” ๋ฌธ์ž ํ•ด์ฒด๋ถ„์„ ๊ธฐ๋Šฅ์„ ํ•จ์ˆ˜๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์„ ์ด์•ผ๊ธฐํ•œ๋‹ค.

    ์ด๋Š” template literals๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

     

    ์˜ˆ์‹œ

    let val = "Korea";
    
    function func(strings, values){
      console.log(strings);
      console.log(values);
    }
    
    func`Welcome to ${val}!`

     

    ์œ„์˜ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด

    func๋ผ๋Š” ํ•จ์ˆ˜์— ๋ฐฑํ‹ฑ( ` )์œผ๋กœ ๊ฐ์‹ธ์ง„ ๋ฌธ์ž์—ด์„ ๋ถ™์ธ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

    ์ด๊ฒƒ์ด ๋ฐ”๋กœ tagged literals ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

     

    tagged literals ํ•จ์ˆ˜๋ฅผ ์‚ดํŽด๋ณด๋ฉด 2๊ฐœ์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ

    ์ฒซ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” ๋ฐฑํ‹ฑ ๋‚ด ์ˆœ์ˆ˜ํ•œ ๋ฌธ์ž๋“ค์„ ๋ณ€์ˆ˜ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆ„์–ด Array ํ˜•ํƒœ๋กœ ๋งŒ๋“  ๊ฒƒ์ด๊ณ ,

    ๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” ๋ฐฑํ‹ฑ ๋‚ด ${}๋กœ ๊ฐ์‹ธ์ ธ์žˆ๋Š” ๋ณ€์ˆ˜๋ฅผ ๋‹ด๋Š” ๊ฒƒ์ด๋‹ค.

    ์ด๋•Œ ๋ณ€์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ๊ฐœ์ผ ๊ฒฝ์šฐ์—๋Š” ์—ฌ๋Ÿฌ๊ฐœ์˜ ํŒŒ๋ผ๋งˆํ„ฐ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ฑฐ๋‚˜ restํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ด์šฉํ•œ๋‹ค!

     

     

    ์˜ˆ์‹œ

    let val1 = "Korea";
    let val2 = "USA";
    let val3 = "Japan";
    
    function func(strings, ...values){
      console.log(strings);
      console.log(values);
    }
    
    func`Welcome to ${val1} and ${val2} and ${val3}!`

     

     

    ์ด์ฒ˜๋Ÿผ ๋ณ€์ˆ˜ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆˆ Array์™€

    ์—ฌ๋Ÿฌ๊ฐœ์˜ ๋ณ€์ˆ˜๋ฅผ ๋‹ด์€ Array๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

     

     

    ์ด ๊ฒฐ๊ณผ๊ฐ’์„ ์ด์šฉํ•˜์—ฌ ๋ฌธ์ž์˜ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์–ด ๋ฐ˜ํ™˜ํ•˜๊ฑฐ๋‚˜ ์ผ๋ถ€ ๋ฌธ์ž๋งŒ ์ถ”์ถœํ• ์ˆ˜ ์žˆ๋‹ค.

     

     

    let val1 = "Korea";
    let val2 = "USA";
    let val3 = "Japan";
    
    function func(strings, ...values){
      console.log(`We are going to ${values[2]} and ${values[1]} this Summer`);
    }
    
    func`Welcome to ${val1} and ${val2} and ${val3}!`
    
    
    --------
    "We are going to Japan and USA this Summer"

     

    ๋Œ“๊ธ€