본문 바로가기
반응형

프로그래밍 개발/JS ES6+19

Javascript ES6+ Promise Promise Promise의 상태 unnsettled (미확정) 상태: pending. thenable하지 않다. settled (확정) 상태: resolved. thenable한 상태다. - fulfilled (성공) - rejected (실패) const promiseTest = param => new Promise((resolve, reject)=> { setTimeout(()=> { if(param) { resolve("해결") } else { reject(Eroor("실패")) } }, 1000) }) const testRun = param => promiseTest(param) .then(text => { console.log(text)}) //.then은 resolve 의미로 성공했을 때 .. 2020. 12. 22.
Javascript ES6+ Class Class ES5의 프로토타입 메소드 대신 ES6+에서 더 편히라게 쓸 수 있는 Class 가 생겨났다. class의 기본 쓰임 // 클래스 리터럴 class Person1 { } console.log(Person1.name) // 기명 클래스 표현식 const Person2 = class Person22 { } console.log(Person2.name) // 익명 클래스 표현식 let Person3 = class { } console.log(Person3.name) ES5 버전의 프로토타입 function Person1 (name) { this.name = name } Person1.prototype.getName = function () { //prototype 메소드이다. return this... 2020. 12. 21.
Javascript ES6+ Generator Generator 중간에서 멈췄다가 이어서 실행할 수 있는 함수. function 키워드 뒤에 `*`를 붙여 표현하며, 함수 내부에는 `yield` 키워드를 활용한다. 함수 실행 결과에 대해 `next()` 메소드를 호출할 때마다 순차적으로 제너레이터 함수 내부의 `yield` 키워드를 만나기 전까지 실행하고, `yield` 키워드에서 일시정지한다. 다시 `next()` 메소드를 호출하면 그 다음 `yield` 키워드를 만날 때까지 함수 내부의 내용을 진행하는 식이다. 선언 방식 function* gene () { yield } const gene = function* () { yield } const obj = { gene1: function* () { yield } //메소드 함수 가능 *gene2 .. 2020. 12. 18.
Javascript ES6+ Iterator Iterator 반복을 위해 설계된 특별한 인터페이스를 가진 객체라고 할 수 있다. - 객체 내부에는 `next()` 메소드가 있는데, - 이 메소드는 `value`와 `done` 프로퍼티를 지닌 객체를 반환한다. - `done` 프로퍼티는 boolean값이다. Iterator 구현 예시 코드 객체 내의 프로퍼티를 iterable한 개체로 활성화 시켜주는 것을 확인 할 수 있다. const iter = { items : [10, 20, 30], count: 0, next () { const done = this.count >= this.items.length return{ done, value: !done ?this.items[this.count++]:undefined } } } console.log(i.. 2020. 12. 18.
Javascript ES6+ Iterable Iterable Iterable의 정의 내부 요소들을 공개적으로 탐색(반복)할 수 있는 데이터 구조. [Symbol.iterator] 메소드를 가지고 있다. 아래와 같은 코드들이 iterable한 예이다. const arr = ['a', 'b', 'c'] const set = new Set(['a', 'b', 'c']) const map = new Map([[false, 'no'], [true, 'yes'], ['well', 'soso']]) const str = '문자열도 이터러블하다' ※ Iterable의 의미는 내부 요소들을 공개적으로 반복 및 탐색할 수 있는 데이터 요소를 뜻한다. [Symbol.Iterable] 매소드를 가지고 있는 것이 특징이다. 개체 자신이 iterable한 경우 array,.. 2020. 12. 18.
Javascript ES6+ Map Map Map을 쓰는 이유 중 하나는 객체의 단점을 보안하기 위한 것이다. 객체의 단점 iterable하지 않다. (iterable의 의미는 순서대로 순환 및 반복한다는 흐름이다) 키를 문자열로 취급한다. 키값의 unique함을 완벽히 보장하지 못함. 프로퍼티 개수를 직접 파악할 수 없다. iterable하지 않다. const o = { a: 1, b: 2, c: 3 } for (let key in o) { console.log(key, o[key]) } /결과: // a 1 // b 2 // c 3 Object.prototype.method = function () { } for (let key in o) { console.log(key, o[key]) } //결과: //a 1 //b 2 //c 3 /.. 2020. 12. 16.
Javascript ES6+ Set set Array.prototype.pushUnique = value =>{ if(!this.include(value)){ this.push(value) } }return this const arr = [1, 2, 3] arr.pushUnique(5) arr.pushUnique(4) arr.pushUnique(3) console.log(arr) //결과: arr(5) {1, 2, 3, 5, 4} ///// const set = new Set([1,2,3]) set.add(5) set.add(4) set.add(3) console.log(set) //결과:Set(5) {1, 2, 3, 5, 4} set은 중복이 허용되지 않으며 순서를 보장하는, 값들로만 이루어진 리스트를 만드는 역할을 한다. 위의 결과를 .. 2020. 12. 16.
Javascript ES6+ 심볼(Symbol) 심볼(Symbol) primitive value => 유일무이하고 고유한 존재. 비공개 멤버에 대한 needs에서 탄생. 기본적인 열거대상에서 제외. 암묵적 형변환 불가. `Symbol([string])` : 문자열이 아닌 타입은 자동으로 toString 처리한다. const sb1 = Symbol() const sb2 = Symbol() console.log(sb1,sb2) console.log(sb1 === sb2) //결과: 오류 const sb1 = Symbol('symbol') const sb2 = Symbol('symbol') console.log(sb1, sb2) console.log(sb1 === sb2) //결과: //Symbol(symbol) Symbol(symbol) //false c.. 2020. 12. 15.
Javascript ES6+ Destructuring assignment Destructuring assignment 배열의 해체할당 var colors = ['red', 'white', 'orange'] var first = colors[0] var second = colors[1] var third = colors[2] console.log(first, second, third) //결과: red white orange const colors = ['red', 'white', 'orange'] const [first, second, third] = colors console.log(first, second, third) //결과: red white orange 위의 두 코드의 결과는 똑같다. ES6+부터는 변수 이름을 배열화할 수 있게 되었다. const colors = .. 2020. 12. 14.
Javascript ES6+ Function 함수 Function 함수 name property function a () { } console.log(a.name) //결과: // a 위 코드는 name 프로퍼티가 함수 a에 붙어 문자열로 'a'가 출력된다. 함수가 name 프로퍼티를 가지고 있기 때문에 가능한 일이다. const b = function () { } console.log(b.name) //결과: b const c = function cc () { } console.log(c.name) //결과: cc const d = () => {} console.log(d.name) //결과: d const e = { om1: function () {}, om2 () {}, om3: () => {} } console.log(e.om1.name, e.o.. 2020. 12. 14.
Javascript ES6+ Arrow Function Arrow Function var a = function () { return new Date() } var b = function (a) { return a * a } var c = function (a, b) { return a + b } var d = function (a, b) { console.log( a * b ) } const f = funtion () { a: 1, b: 2 } ↓ let a = () => new Date() let b = a => a * a let c = (a, b) => a + b let d = (a, b) => { console.log( a * b ) } const f = () => ({ a: 1, b: 2 }) 위와 같이 function()이라는 함수를 Arrow F.. 2020. 12. 11.
Javascript ES6+ 객체의 향상된 기능들 객체의 향상된 기능들 shorthand property var x = 10 var y = 20 var obj = { x: x, y: y const x = 10 const y = 20 const obj = { x, y 두 코드를 비교해보면 ES6+의 새로운 기능추가로 프로퍼티가 축약된 것을 확인 할 수있다. 또 프로퍼티의 key와 value에 할당할 변수명이 동일한 경우 value 생략 가능하다. const convertExtension = function (fullFileName) { const fullFileNameArr = fullFileName.split('.') const filename = fullFileNameArr[0] const ext = fullFileNameArr[1] && fullFi.. 2020. 12. 11.
Javascript ES6+ spread operator (펼치기 연산자) spread operator (펼치기 연산자) var birds = ['eagle', 'pigeon'] var mammals = ['rabbit', 'cat'] var animals = birds.concat('whale').concat(mammals) console.log(animals) const animals2 = [...birds, 'whale', ...mammals] console.log(animals2) //결과: //["eagle", "pigeon", "whale", "rabbit", "cat"] //["eagle", "pigeon", "whale", "rabbit", "cat"] 위와 같이 .concat이라는 메소드를 쓰지 않고도 더 효율적으로 배열을 만들어 낼 수 있다는 것을 볼 수 있다.. 2020. 12. 9.
Javascript ES6+ rest parameter (나머지 매개변수) rest parameter(나머지 매개변수) 구 버전인 ES5에서 썼던 배열을 만들어 주는 argumernt 대신 "...(매개변수)"을 쓴다면 더 쉽게 배열을 만들 수 있다. ...(매개변수) const f = function (x, y, ...rest) { console.log(rest) } f(1, 2, true, null, undefined, 10) //결과; //[true, null, undefined, 10] 위의 결과를 보면 rest 매개변수를 호출한 결과 ...rest만 해줘도 모든 정의된 값들이 배열로서 결과가 나온다는 것을 알 수 있다. const f = function (...rest) { console.log(rest) } f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .. 2020. 12. 9.
Javascript ES6+ default parameter (매개변수 기본값) default parameter (매개변수 기본값) 과거 버전인 ES5과 다르게 매개변수의 활용의 기능이 늘었다. //결과: //0 null //결과: //7 0 "" false null 6 위의 코드들의 결과를 보면 알 수 있듯이 함수의 매개변수로 들어가는 값들이 정의되지 않는다면 그 정의되지 않은 매개변수의 함수 인자들이 자신 스스로 변수로 선언하여 변수 값들을 실행하는 것을 볼 수 있다. 하지만 정의되어진 값들이 매개변수로 들어가면 자기 스스로 변수로 설정한 값들은 무시되며 정상적으로 함수 안에서 매개변수로서 활동한다. 값 주고 받기 const f = function (x = 1, y = 3 + x) { console.log(x, y) } f() //결과: //1 4 위와 같이 함수의 인자들은 매개.. 2020. 12. 9.
Javascript ES6+ template literal template literal console.log(`a bb ccc`) const a = 10 const b = 20 const str = `${a} + ${b} = ${ a + b }` console.log(str) backtick (`) 이라는 문자로 문자를 묶어주면 띄어쓰기, 빈 텍스트, 줄 바꿈 등을 따로 명령어를 사이에 입력을 하지 않아도 실제 타이핑하는 것처럼 표현할 수 있다. 또 backtick (`) 안에 있다는 조건하에 ${}로 값을 묶어주면 연산 또한 가능하다. 응용 const counter = { current: 0, step: 1, count: function() { return this.current += this.step }, reset: function() { return t.. 2020. 12. 8.
Javascript ES6+ forEach, map, reduce 메소드 forEach, map, reduce 메소드 forEach Array.prototype.forEach(callback[, thisArg]) callback : function (currentValue[, index[, originalArray]]) currentValue : 현재값 index : 현재 인덱스 originalArray : 원본 배열 thisArg : this에 할당할 대상. 생략시 global객체 for문을 돌리는 것이랑 같은 개념이다. const a = [ 1, 2, 3 ] a.forEach(function (v, i, arr) { console.log(v, i, arr, this) }, [ 10, 11, 12 ]) //결과: //1 0 [1, 2, 3] [10, 11, 12] //2 1.. 2020. 12. 8.
Javascript ES6+ block scoped variables block scoped variables let var달리 재선언이 불가능하지만 재할당은 가능하다. 블록 스코프로 적용되어 외부에서 접근할 수 없다. let a = 1 a = 2 console.log(a) let은 재할당이 가능하다. let 블록 범위 let a = 1 function f () { console.log(a, b, c) // TZD 존이므로 에러가 발생한다. let b = 2 console.log(a, b, c) // 이미 선언된 let b로 인해 b는 2가 호출되지만 a또한 내부에 있지 않지만 // 외부에 선언되어있어 호출된다. 하지만 c는 아직 선언조차 되지 않았다. if (true) { let c = 3 console.log(a, b, c)// a도 호출되고 let c로 인해 c 또한.. 2020. 12. 7.
Javascript ES6+ Block Scope Block Scope 함수 스코프는 함수의 인해서 생기는 범위, 변수의 유효범위를 뜻하지만 블록 스코프(Block Scope)는 블락 '{}' 에 인해서 생기는 유효범위라고 말할 수 있다. 즉 { }에 인해서 변수의 유효범위가 결정된다. {}의 범위 { let a = 10 { let a = 20 console.log(a) } console.log(a) } console.log(a) 위의 결과를 보면 첫 번째와 두 번째 a의 값은 정의되어있다는 것을 알 수 있다. 즉 첫 번째와 두 번째로 a를 호출한 범위가 {} 블록 안에서 있기 때문에 정의될 수 있다. 하지만 세 번째 a호출은 {}블락 범위 안에 있지 않고 외부에 있기 때문에 a가 정의되지 않아 에러가 발생한다. 이점이 ES5와 ES6+의 다른점이라고 .. 2020. 12. 7.
반응형