이채현
💡 Javascript ES6 문법을 배워보자 - 문자열
Strings Template Literal variable을 가진 문자열을 쓰는 방법에 대한 개선
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const sayHi = (aName = "anon" ) => { return "Hello " + aName; }; ==> const sayHi = (aName = "anon" ) => { return `Hello ${aName} ` ; } const add = (a, b ) => a + b;console .log (`hello how are you ${add(6 , 6 )} ` );
HTML Fragments 1 1 2 3 4 5 6 7 8 9 10 11 const wrapper = document .querySelector (".wrapper" );const addWelcome = ( ) => { const div = document .createElement ("div" ); const h1 = document .createElement ("h1" ); h1.innerText = "Hello" ; div.append (h1); wrapper.append (div); }; setTimeout (addWelcome, 1000 );
⇒
1 2 3 4 5 6 7 8 const addWelcome = ( ) => { const div = ` <div class="hello"> <h1>Hello</h1> </div> ` ; wrapper.innerHTML = div; };
template literal은 ``` … space를 고려한다.
HTML Fragments 2 1 2 3 4 5 6 7 8 9 10 const alphas = ["A" , "B" , "C" , "D" ];const ul = document .createElement ("ul" );const list = ` <h1>Alphabet</h1> <ul> ${alphas.map(alpha => `<li>${alpha} </li>` ).join("" )} </ul> ` ;wrapper.innerHTML = list;
Cloning Styled Components 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 const styled = (aElement ) => { const el = document .createElement (aElement); return (args ) => { const styles = args[0 ]; el.style = styles; return el; }; }; const title = styled ("h1" )` background-color: red; color: blue; ` ;const subTitle = styled ("span" )` color: green; ` ;title.innerText = "We just cloned" ; subTitle.innerText = "Styled Components" ; document .body .append (title, subTitle);
More String Improvements 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const isEmail = (email ) => email.includes ("@" );console .log (isEmail ("[email protected] " )); console .log (isEmail ("myEmail" )); const CC_NUMBER = "6060" ; const displayName = `${"*" .repeat(10 )} ${CC_NUMBER} ` ;console .log (displayName); const name = "Mr. abc" ;console .log (name.startsWith ("Mr" )); console .log (name.endsWith ("abc" ));