문법과 어휘구조2(ES6~new)
Template literal, for..of, Arrow Function, Rest, Spread,destructuring 등 새로 등장한 문법을 학습한다.
let template = ` "" 도 쓸 수 있고, '' 도 쓸수있다. `; console.log(template);let firstName = "Bo-Hun"; let lastName = "Kim"; let fullName = `${firstName} + ${lastName}`; console.log(fullName);let exampleNumber1 = 1; let exampleNumber2 = 2; let sumOfExampleNumber = `${exampleNumber1 + exampleNumber2}`; console.log(sumOfExampleNumber);
let noParameter = () => { console.log("매개 변수가 없는경우");}; let oneParameter = x => {console.log(x);}; let multiParameter = (x,y) => { console.log(x+y)}; let oneLineFunction = x => x*x; let returnObjectFunction = () => ({ x : 5 }); let multiLineArrowFunction = () => { console.log("여러줄 선언이 된다."); console.log("여러줄 선언이 된다."); console.log("여러줄 선언이 된다."); console.log("여러줄 선언이 된다."); console.log("여러줄 선언이 된다."); } noParameter(); oneParameter(5); multiParameter(1,3); console.log(oneLineFunction(5)); console.log(returnObjectFunction()); console.log(multiLineArrowFunction()());// ES5 var arr = [1, 2, 3]; var pow = arr.map(function (x) { // x는 요소값 return x * x; }); console.log(pow); // [ 1, 4, 9 ] // ES6 const arr = [1, 2, 3]; const pow = arr.map(x => x * x); console.log(pow);let person = { name: 'Lee', sayHi: () => console.log(`Hi ${this.name}`) }; person.sayHi(); // undefined person = { name: 'Lee', sayHi() { console.log(`Hi ${this.name}`); } // 축약 메서드 표현 }; person.sayHi(); // Hi Lee
// 배열 for (const item of ['a', 'b', 'c']) { console.log(item); } // 문자열 for (const letter of 'abc') { console.log(letter); } // Map for (const [key, value] of new Map([['a', '1'], ['b', '2'], ['c', '3']])) { console.log(`key : ${key} value : ${value}`); // key : a value : 1 ... } // Set for (const val of new Set([1, 2, 3])) { console.log(val); } // 내부적으로 어떻게 동작하는지 for 로 표현하면 다음과 같다. // 이터러블 const iterable = [1, 2, 3]; // 이터레이터 const iterator = iterable[Symbol.iterator](); for (;;) { // 이터레이터의 next 메소드를 호출하여 이터러블을 순회한다. const res = iterator.next(); // next 메소드가 반환하는 이터레이터 리절트 객체의 done 프로퍼티가 true가 될 때까지 반복한다. if (res.done) break; console.log(res); }
const arr = [1, 2, 3]; /* 배열의 인덱스를 기준으로 배열로부터 요소를 추출하여 변수에 할당 변수 first, second, third 선언되고 arr(initializer(초기화자))가 Destructuring(비구조화, 파괴)되어 할당된다. */ const [first, second, third] = arr; /* 디스트럭처링을 사용할 때는 반드시 initializer(초기화자)를 할당해야 한다. const [first, second, third]; // SyntaxError: Missing initializer in destructuring declaration */ console.log(first, second, third); // 1 2 3
const obj = { firstName: 'Ungmo', lastName: 'Lee' }; const { lastName, firstName } = obj; console.log(firstName, lastName); // Ungmo Leeconst { prop1: p1, prop2: p2 } = { prop1: 'a', prop2: 'b' }; console.log(p1, p2); // 동일한 표현이나 좀더 축약하면 다음과 같다. const { prop1, prop2 } = { prop1: 'a', prop2: 'b' }; console.log({ prop1, prop2 }); // default value 를 destructure 에 정할수 있다. const { prop1, prop2, prop3 = 'c' } = { prop1: 'a', prop2: 'b' }; console.log({ prop1, prop2, prop3 });const todoList = [ { id: 1, content: 'HTML', completed: true }, { id: 2, content: 'CSS', completed: false }, { id: 3, content: 'JS', completed: false } ]; // java8 stream 에서 확인했던, 그 메서드와 기능상으로 매우 동일했다. const completedTodoList = todoList.filter(({ completed }) => completed); console.log(completedTodoList);const person = { name: 'Kim', address: { zipCode: '00000', city: 'Seoul' } }; const { address: { city } } = person; console.log(city);
function defaultValueInParameter(x=0, y=1){ return x+y; }// 일반적인 형태이며 가변인자를 배열 형태로 받는다. function restParameterFunction(...rest){ console.log(Array.isArray(rest)); console.log(rest); return rest.reduce((first, second) => first + second); } // 반드시 제일 마지막에 위치하지 않으면 Syntax Error 발생 function parameterCombination(first,second, ...rest){ console.log(Array.isArray(rest)); console.log(rest); }
console.log(...[1, 2, 3]); // 1, 2, 3 console.log(...'Hello'); // H e l l o console.log(...new Map([['a', '1'], ['b', '2']])); // [ 'a', '1' ] [ 'b', '2' ] console.log(...new Set([1, 2, 3])); // 1 2 3 console.log(...{ a: 1, b: 2 }); // 이터러블이 아닌 일반 객체는 Spread 문법의 대상이 될 수 없다.const arr = [1, 2, 3]; function foo(x, y, z) { console.log(x); console.log(y); console.log(z); } foo(...arr);
const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const returnedTarget = Object.assign(target, source); console.log(target); // Object { a: 1, b: 4, c: 5 } console.log(returnedTarget); // Object { a: 1, b: 4, c: 5 }// Spread Property const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; console.log(target); console.log(source); const merge = { ...target, ...source }; console.log(merge); console.log(target); // Rest Property const {single, ...collection} = merge; // 객체의 병합 const merged = { ...{ x: 1, y: 2 }, ...{ y: 10, z: 3 } }; console.log(merged); // { x: 1, y: 10, z: 3 } // 특정 프로퍼티 변경 const changed = { ...{ x: 1, y: 2 }, y: 100 }; console.log(changed); // { x: 1, y: 100 } // 프로퍼티 추가 const added = { ...{ x: 1, y: 2 }, z: 0 }; console.log(added); // { x: 1, y: 2, z: 0 }
Last updated