2부는 사실 43분이다

 

  • 형태 : 'abcde', "abcde", `abcde`, `abcde${변수명}`

`Template literal 템플릿 리터럴` 기호이름은 백틱 backtick

let x = 'acd'
let x = "acd"
let x = `acd`
//뭘 해도 결과값은 'acd'

`abcde${변수명}`예시

let name = 'baeggoose'
let age = 109

console.log('제 이름은' + name + '입니다. 제 나이는' + age + '입니다.')
제 이름은baeggoose입니다. 제 나이는109입니다
//번거로움.

console.log(`제 이름은 name 입니다. 제 나이는 age 입니다.`)
제 이름은 name 입니다. 제 나이는 age 입니다
//변수로 인식을 못함.

console.log(`제 이름은 ${name} 입니다. 제 나이는 ${age} 입니다.`)
제 이름은 baeggoose 입니다. 제 나이는 109 입니다
//템플릿 리터럴. ${변수}를 인식함
  • 호출 : 변수명, 변수명[0] (변수명[index], 호출은 할 수 있지만 개별 값 변경 불가)
name
'baeggoose'

name[1]
'a'
//인덱싱한다.

name.length
9

name.slice(2,)
'eggoose'
//2번째까지 잘라냄.

name.replace('baeg','peng')
'peng goose'
//백 구스를 펭 구스로 바꿈

'baeg goose baeg'.replace(/baeg/g,'peng')
'peng goose peng'
//g는 글로벌하게 이 안에 있는 모든걸 뜻함
  • 메서드 (다 중요하댔음) :
    • str.length
    • str.indexOf()
    • str.lastIndexOf()
    • str.includes()
    • str.slice()
    • str.splice()
    • str.split()
    • str.substring()
    • str.substr()
    • str.toLowerCase()
    • str.toUpperCase()
    • str.trim()
    • str.replace()
    • str.concat()
    • str.repeat()
    'hello'.repeat(100)
    
    '0'.repeat(100)
    0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    
    '0'.repeat(100).split('')
    (100) ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
    
    '5'.repeat(100).split('').map(Number)

밑에껀 알고리즘 문제 풀때나 급할때 사용한다

 

  • Boolean(논리값)
    • 형태 : true, false
    • 호출 : 변수명
    • 어떤 것이 true이고 어떤 것이 false인지 판단할 수 있어야 합니다.(truthy, falsy -> 우리가 매우 깊이 다뤘던 내용입니다.)
let x = true
undefined
//'따옴표' 안쓴게 주의점, 다른 언어에서는 T 대문자로 쓰기도 한다.

!![]
true
!!{}
true
//둘 다 다른 언어에서는 false다

!!''
false
//아무것도 없으면 false

!!'hello'
true

!!0
false
!!10
true
!!-10
true
//0을 제외한 숫자는 모두 true
  • undefine : undefind
    • 형태 : let a, console.log(a)
let x
undefined
x
undefined
  • null : object
    • 형태 : let a = null
x = null
null

ex) 반에서 누가 전학간다고 번호가 당겨지지 않는다 그럴때 없음을 명시해준다

  • Array(배열) : object
    • 형태 :
['하나', '둘', '셋']
[100, 200, 300]

[{'one':1, 'two':2}, {'one':10, 'two':20}]//실무에서 많이 보이는 형태.
let x = [{'one':1, 'two':2}, {'one':10, 'two':20}]
undefined
x[1]
{one: 10, two: 20}
x[1]['one']
10

[[10, 20], [100, 200], [1000, 2000]]
// 3차원

let x =[[[1, 2], [10, 20], [100, 200]],
 [[3, 4], [30, 40], [300, 400]]]
 //400을 꺼내고 싶다.
 
 x[1]
	(3) [Array(2), Array(2), Array(2)]
		0: (2) [3, 4]
        1: (2) [30, 40]
        2: (2) [300, 400]
        length: 3
        [[Prototype]]: Array(0)
        
x[1][2]
(2) [300, 400]

x[1][2][1]
400

 

이게 왜 중요하냐? JSON로 실무에서 쓰는 데이터를 생성할 때

 

Array의 Depth가 얕지 않고 점점 더 깊어지므로 접근하는 방식을 알아야 하기 때문이다

 

  • 호출 : 변수명, 변수명[0], 변수명[0][0] (변수명[index], 개별값 변경 가능)
  • Array
  • 메서드 :
    • length
    • forEach
x=[10,20,30,40]
(4) [10, 20, 30, 40]

x.forEach(x => console.log(x ** 2))

VM2147:1 100
VM2147:1 400
VM2147:1 900
VM2147:1 1600
  • map //많은 데이터들 중 데이터를 뽑아 낼 때 사용한다
[10,20,30,40].map(x => x+100)
(4) [110, 120, 130, 140]
//새로운 배열을 만들어준다
  • filter
[1,2,3,5,7,9].filter(x => x > 4)
(3) [5, 7, 9]

 

  • push / pop - mutable
  • slice - immutable
  • splice - mutable
  • reduce - immutable
  • join
  • indexOf
  • includes
  • find
[1,2,3,5,7,9].find(x => x > 4)
5

 

  • concat
  • every
  • some
  • fill — mutable
  • shift — mutable
  • unshift — mutable
  • reverse — mutable
  • sort — mutable
Array(100).fill(0)
Array(100).fill('hello')
Array(100).fill('hello'.repeat(2))
Array(100).fill(0).map((value, index)=> value + index)

Array(100)
(100) [empty × 100]//비어있음

Array(100).fill(0)
(100) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Array(100).fill(0).map((value, index)=> value + index + 1)
(100) [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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

Array(100).fill(0).map((value, index)=> value + index + 100)
(100) [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199]
  • Object(객체)
    • 형태 : 키와 밸류 (feat.운영 중단된 라이브 코로나 사이트)
{
    "지역이름": "전국", // key : value(2개의 집합을 가리켜 객체 프로퍼티).
    "확진자수": 24889,
    "격리해제수": 23030,
    "사망자수": 438,
    "십만명당발생율": 48.0
}
{
    'one' : 1,
    'o n e' : 1,
    '1 one' : 1
}
{
    one : 1,
    o n e : 1, // error.
    1 one : 1 // error.
}
let x=1, y=2, z=3
let object = {x, y, z} // {x: 1, y: 2, z: 3}.
  • 호출 : 변수명, 변수명.지역이름, 변수명['지역이름'] (변수명.key, 변수명[key])

변수명[x]가 안되는 이유는 x를 변수로 인식할 수 있기 때문이다

  • 수정 : value['hello'] = 'world', value['hello'] = null
  • 삭제 : delete value['hello']는 추천하지 않음(메모리 상에 'world'가 남아있음, value['hello'] = null을 권장)
  • 메서드 : Object.keys(키값만 출력), Object.values(오브젝트값만 출력), Object.entries(다 출력)
//변수명.keys()와 같은 형식은 안됩니다.
x.keys()
  • Map : object
    • 메서드 : set, get, has, delete, size
let map = new Map()
map.set('one', 100)
map.set('two', 200)
map.set('three', 300)
map.set('four', [10, 20])//map.keys(),values(),entries() 오브젝트랑 똑같이쓸수있음.

map.set(5, [100, 200])
map.set([1, 2], [100, 200])
map.get(5)

let human = {
    name:'hojun3',
    age:30,
    local:'jeju'
}
let hojun = new Map(Object.entries(human))

let test = new Map(Object.entries(Object))//오브젝트에 접목
  • Set : object
    • 메서드 : add, delete, has, size
    • 중복을 허락하지 않는다
    • 합집합, 교집합, 차집합 등에 메서드가 있진 않지만, 이러한 합집합, 교집합, 차집합을 구현하기 위해 Set을 사용하는 경우가 많습니다
let set = new Set('11111222233333')
undefined
set
Set(3) {'1', '2', '3'}//중복 허락안함
set.add(5);
Set(4) {'1', '2', '3', 5}//추가
set.add(7);
Set(5) {'1', '2', '3', 5, 7}
set.size
5

조건문과 반복문

조건문

  • if
  • else if
  • else
  • switch
if(false) {
    console.log('hello 1')
}
if(false) {
    console.log('hello 2')
}
if(true) {
    console.log('hello 3')
}
if(true) {
    console.log('hello 4')
}
//트루인 것만 출력

let x =2

if(10 % x == 0)//변수를 넣을 수 있다
true
if(false){//(true)면 헬로 원을 실행시킨다 그런데 false이므로 밑의 else로 간다
    console.log('hello 1')
}
else if(false) {//마찬가지로 트루여야하는데 아님
    console.log('hello 2')
}
else if(true) {//트루가 맞음 헬로3이 실행된다
    console.log('hello 3')
}
else if(true) {//그렇지 않을 때 실행되는데 이미 트루가 나와서 위에만 출력
    console.log('hello 4')
}
else {
    console.log('!!')
}
let result = true ? 1 : 100;

result
1
//결과가 트루일 때 앞의 값을 출력한다.

true ? console.log('one') :
    console.log('two');
one

false ? console.log('one') :
    console.log('two');
two
let day
switch (new Date().getDay()) {
  case 0:
    day = "일";
    break; //케이스 0에서 멈춘다
  case 1:
    day = "월";
    break;
  case 2:
    day = "화";
    break;
  case 3:
    day = "수";
    break;
  case 4:
    day = "목";
    break;
  case 5:
    day = "금";
    break;
  case 6:
    day = "토";
}
console.log(day)
일

반복문

  • for
  • for in
  • for of
  • while
  • do while
  • forEach
  • break
  • continue
for (let i = 0; i < 10; i++) {
    console.log(i)
}
0
VM3516:2 1
VM3516:2 2
VM3516:2 3
VM3516:2 4
VM3516:2 5
VM3516:2 6
VM3516:2 7
VM3516:2 8
VM3516:2 9

for( let i = 5; i < 10; i++){
    console.log(i)
}
VM3574:2 5
VM3574:2 6
VM3574:2 7
VM3574:2 8
VM3574:2 9
undefined
for( let i = 5; i < 10; i = i +2){
    console.log(i)
}
VM3601:2 5
VM3601:2 7
VM3601:2 9

for( let i = 5; i < 10; i = i +2){
    for( let k = 6; k < 10; k++){
    console.log(`${i} x ${k} = ${i*k}`)
    }
} //for문이 중첩되는 경우가 굉장히 많다
VM4113:3 5 x 6 = 30
VM4113:3 5 x 7 = 35
VM4113:3 5 x 8 = 40
VM4113:3 5 x 9 = 45
VM4113:3 7 x 6 = 42
VM4113:3 7 x 7 = 49
VM4113:3 7 x 8 = 56
VM4113:3 7 x 9 = 63
VM4113:3 9 x 6 = 54
VM4113:3 9 x 7 = 63
VM4113:3 9 x 8 = 72
VM4113:3 9 x 9 = 81
//for of
let a = [10, 20, 30, 40];
for (let i of a) {
    console.log(i);
}
10
20
30
40

let a = 'hello';
for (let i of a) {
    console.log(i);
}
h
e
2l
o
let s = 0
let a = '19821'
for (let i of a) {
    s += i //s는 i를 누적한다
}
'019821'
s
'019821'

let s = 0
let a = '19821'
for (let i of a) {
    s += parseInt(i)
}
21
let a = {'one':1, 'two':2};
for (let i in a) {
    console.log(i);
}
one
two//키값만 출력한다 밸류는 log(a[i]);
let x = 0;
while (x < 10) {
    console.log(x);
    x++; //x는 증가한다는 전제가 꼭 있어야 한다 안 그럼 무한반복된다
}

 

호기심에 x++지우고 했다가 컴퓨터 멈출 뻔;

 

//예제
for (let i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    console.log(i)
}
0
1
2
3
4

 

break 은 반복문을 탈출하고

 

for (let i = 0; i < 10; i++) {
    if (i == 5) continue;
    console.log(i);
}
0
1
2
3
4
6
7
8
9

 

continue 은 다음 루프로 넘어간다

 

함수와 클래스

함수

  • 함수 표현식과 함수 선언식
let 함수표현식 = function(){} // 호이스팅 X(let ,class 등 일시적 사각지대에 빠질 수 있다)
function 함수선언식(){} // 호이스팅 O
  • 함수(파선아실: 파라미터는 선언할 때, 아규먼트는 실제 사용하는 값이다)
    • 여기서 x, y를 보통 한국에서는 인자
    • 매개변수(파라미터, parameter) : x, y
    • 전달인자(아규먼트, argument) : 3, 5
    • 사용이유
      1. 재사용성
      2. 아키텍처 파악
      3. 유지보수
function add(x, y){
    return x + y; //x,y에 값을 돌려 놓는다
}

add(3, 5)

function add(a = 100, b = 200) {
    console.log(a, b);
    return a + b;
}

add(10, 20);
// 30
add(10);
// 210
add(); //디폴트 값대로
// 300
add(b=300) // a에 입력
// 500
add(undefined, 300);
// 400

function add({ a = 100, b = 200 }) {
    console.log(a+b);
}

add({b: 300}); // 400
  • 콜백함수 : 아규먼트를 먼저 주고 나중에 실행시키겠다
function add(x, y) {
    return x + y;
}

function mul(x, y) {
    return x * y;
}

function cal(a, b){
    return a(10, 10) + b(10, 10);
}

cal(add, mul); // 함수를 변수처럼 실행시킨다
  • 화살표 함수를 콜백함수로 사용했을 경우의 장단점
    • 장점 : 네이밍을 안해도 됩니다.
    • 장점 : 다른 곳에서 사용할 수가 없다.
    • 단점 : 콜백지옥에 빠질 수가 있습니다.
function cal(a, b){
    return a(10, 10) + b(10, 10);
}

cal((a, b) => a + b, (a, b) => a * b);
  • 화살표함수
function 제곱(x) {
    return x**2
}

// 함수표현식, 호이스팅 X
let 제곱 = x => x**2; //리턴값 x**2; 인자값이 하나일 때

function f(a, b) { //인자값 여러개일때
    let z = 10
    let result = z + a + b
    return result
}

// 함수표현식, 호이스팅 X
let f = (a, b) => {
    let z = 10
    let result = z + a + b
    return result//리턴값 여러개 일 때
};

클래스

  • 클래스 - 붕어빵 찍는 틀, 공장
  • 인스턴스 - 붕어빵, 제품
class Notice {
    constructor(title, contents, author){ //constructor는 고정이다
        this.title = title
        this.contents = contents
        this.author = author
    }
    수정하기(title, contents, author){
        this.title = title
        this.contents = contents
        this.author = author
    }
}
//이게 클래스 밑에 게시글이 인스턴스
dataBase = []
게시물1 = new Notice('제목1', '내용1', '저자1')
dataBase.push(게시물1)
게시물2 = new Notice('제목2', '내용2', '저자2')
dataBase.push(게시물2)
게시물3 = new Notice('제목3', '내용3', '저자3')
dataBase.push(게시물3)

dataBase.forEach(d => {
    제목 = document.createElement('h1')
    제목.textContent = d.title
    내용 = document.createElement('p')
    내용.textContent = d.contents
    저자 = document.createElement('p')
    저자.textContent = d.author
    document.body.append(제목)
    document.body.append(내용)
    document.body.append(저자)
})

// dataBase.splice()와 같은 것으로 삭제, 실제로는 mongoDB와 같은 곳에서 삭제

예시) 화면에서 가로세로 높이와 같은 큰틀은 같으므로 클래스를 묶는다

class Human {
    constructor() {}
    // 인스턴스 메서드, 인스턴스 프로퍼티 메서드, 프로토타입 메서드
    a() {}
    // 클래스 메서드, 클래스 프로퍼티 메서드, 정적 메서드
    static b() {}
}

hojun = new Human('호준')
//휴먼이라는 클래스는 공격과 방어가 가능한데 어떤 새로운 휴먼을 만들어도 쓸 수 있다

typeof hojun // object
typeof Human // function

// getter - 획득
// setter - 설정
// # = private 필드
 
class Mento extends Student {//상속
    codeReview() {
        console.log('코드리뷰를 진행합니다.');
    }
}

let hojun = new Student(999, '호준', ['python', 'js', '...생략...']);

let hojun2 = new Mento(999, '호준', ['python', 'js', '...생략...']);

예외처리, 전개표현식, 정규표현식, 리터럴 등

예외처리

try {
   xxxx += 10000 //x 가 없는데 누적시킨다 에러
} catch(e) {
   console.log('에러!')
   console.error(e)
} finally {
	console.log('finally!') //무조건 실행시킨다
}
에러!
VM139:5 ReferenceError: xxxx is not defined
    at <anonymous>:2:4 // 빨간 에러 표시
finally!

//throw new Error(message);
//throw new SyntaxError(message);
//throw new ReferenceError(message);

전개구문 사용

  • 전개구문 사용 예제
function f(...x){
    return x;
}

f(1, 2, 3, 4, 5) //여러개의 인자값을 전달해줄때
let arr1 = [1, 2, 3, 4];
let arr2 = [10, 20, 30, 40];
let arr3 = [100, ...arr1, 200, ...arr2, 300]
let arr4 = [100, arr1, 200, arr2, 300]
console.log(arr3)
Math.max(...arr3);//max 값 뽑을때 사용한다
let [a, b, c, ...d] = [10, 20, 30, 40, 50, 60, 70]//10,20,30은 a,b,c,나머지 인자가 ...d가 된다

정규표현식 (어렵대)

// 0 문자 제거
let s = '010100020201020304812123';
s.replace(/[^1-9]/g,"") //꺾쇠는 밖에 있을 때 시작이고,[^와 붙어있을 땐 부정not의 의미
'11221234812123' // 1부터 9까지가 아닌것 0을 집어 내겠다

/*
- `^` : 문자열의 시작
- `$` : 문자열의 종료. 옵션에 따라 문장의 끝 또는 문서의 끝에 매치된다.
- `.` : 임의의 한 문자
- `[]`: 문자 클래스. 문자 클래스 안에 들어가 있는 문자는 그 바깥에서 하나의 문자로 취급된다.
- `^` : 문자 클래스 내에서 ^는 not
- `-` : ex) a-z는 a에서 z까지의 문자
- `|` : or를 나타냄
- `?` : 앞 문자가 없거나 하나 있음
- `+` : 앞 문자가 하나 이상임
- `*` : 앞 문자가 0개 이상임
- `{n,m}` : 앞 문자가 `n`개 이상 `m`개 이하. `{0,1}` 은 `?`와 같은 의미다.
- `{n,}` : 앞 문자가 `n`개 이상. 위의 형태에서 `m`이 생략된 형태이다. `{0,}` 이면 `*`와 같고 `{1,}` 이면 `+`와 같은 의미이다.
- `{n}` : 앞 문자가 정확히 `n`개. `{n,n}` 과 같은 의미이다.
- `()` : 하나의 패턴구분자 안에 서브 패턴을 지정해서 사용할 경우 괄호로 묶어주는 방식을 사용한다.
- `\\\\s` : 공백문자
- `\\\\b` : 문자와 공백 사이를 의미한다.
- `\\\\d` : 숫자 [0-9]와 같다.
- `\\\\t` : 탭문자
- `\\\\w` : 단어 영문자+숫자+_(밑줄) [0-9a-zA-Z_]문자 이스케이프는 대문자로 적으면 반대를 의미한다.
[a-z] : a ~ z 사이의 문자를 찾음
[1-9] : 1 ~ 9 사이의 문자를 찾음
[abc] : a, b, c중 하나를 찾음
[^abc] : a, b, c를 제외한 문자를 찾음
.z : 아무 문자 하나를 . 기호로 찾으며 z로 끝남을 의미
a+ : a가 1개 이상을 의미함
a* : a가 0개 또는 그 이상을 의미함
s : 공백 문자를 찾음(스페이스, 탭 등), 대문자의 경우 아닌 문자를 찾음
d : 숫자를 찾음, 대문자의 경우 아닌 문자를 찾음
w : 알파벳 영문과 숫자와 언더바 _ 기호를 찾음, 대문자의 경우 아닌 문자를 찾음
t : 탭 공간을 찾음
g : 검색범위를 전역으로 확장
i : 대소문자를 구분하지 않음
gi : 검색 범위를 전역으로 확대하면서 대소문자를 구분하지 않음
m : 여러줄을 동시에 매칭함
*/

리터럴

  • 리터럴은 약속된 기호를 사용해 값을 생성하는 것입니다
  • 2진수, 8진수, 16진수 리터럴
    let a = 0b1001
    a == 9 // binary 바이너리 이진법
    let b = 0o1001
    b == 513 // octa 옥타 팔진법
    let c = 0x1001
    c == 4097 // hexa 헥사 십육진법

구조분해할당

for (let [[i, j], k] of [[[1, 2], 2], [[1, 2], 4]]) {
    console.log(i, j);
}

동기와 비동기

  • js는 일을 처리할 수 있는 thread가 1개, 싱글쓰레드라고 함.
  • 하지만 모든 일을 여러명이 처리할 수 없다면 항상 기다려야 하는 문제가 생길 수도 있고, 무한대기에 빠질 수도 있음.
// 순서대로 한다면 덧셈, 곱셈, hello world 순이지만
// 비동기이기 때문에 hello world, 곱셈, 덧셈 순이 됨
function 덧셈(a, b, 콜백함수) {
    setTimeout(()=>{
        let result = a + b
        console.log(result)
    }, 2000)
}
function 곱셈(a, b, 콜백함수) {
    setTimeout(()=>{
        let result = a * b
        console.log(result)
    }, 1000)
}

덧셈(20, 30)
곱셈(2, 6)
console.log('hello world')
//만약 값이 0이 되더라도 헬로월드 먼저 출력된다
  • Promise (중요!)
    • pending(대기상태) - resolve(해결) - fulfilled(성공)
    • pending(대기상태) - reject(거부) - rejected(실패)
new Promise((resolve, reject) => {
        //code 안에서 해결이 되면 then으로 거부가 되면 catch로 간다
    })
    .then(result => result)
    .then(result => result)
    .catch(err => err)
    .finally(result => result) //무조건 실행

let p = new Promise(function(resolve, reject) {
    resolve('hello world');
}).then(메시지 => {
    alert(메시지);
    return 메시지.split(' ')[0]
}).then(메시지 => {
    alert(메시지);
    return 메시지[0]
}).then(메시지 => {
    alert(메시지);
});


const f = fetch('<https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.json>')
f
//Promise {: Response}
const f = fetch('<https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.json>')
    .then(function(response) {
        return response.json();

    })
    .then(function(json) {
        console.log(json);
        return json
    })

const f = fetch('<https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.json>')
    .then(d => d.json())
    .then(d => console.log(d))

//VM458:7 (18) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]0: {시·도별(1): '전국', 총인구 (명): 52980961, 1차 접종 누계: 15199919, 2차 접종 누계: 4521785, 1차 접종 퍼센트: 28.6893984426, …}1: {시·도별(1): '서울', 총인구 (명): 9911088, 1차 접종 누계: 2811191, 2차 접종 누계: 835878, ...중략...

// 뒤에서 나올 DOM api 사용
const f = fetch('<https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.json>')
    .then(data => {
        console.log('데이터 받기 성공!')
        const jsonData = data.json()
        return jsonData
    })
    .then(json => {
        json.forEach(item => {
            console.log(item)
            const h2 = document.createElement('h2')
            h2.innerText = item['시·도별(1)']
            document.body.append(h2)
            const p = document.createElement('p')
            p.innerText = item['총인구 (명)']
            document.body.append(p)
        })
    })
    .catch(e => {
        console.log('json 변환 실패!!')
    })

/////////
// 동기처리 //

setTimeout(()=> {
    console.log('5초 끝!')
}, 5000);

setTimeout(()=> {
    console.log('10초 끝!')
}, 10000);

function cook(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

const myCake = async () => {
    await cook(3000);
    return '케이크';
};

const myCoffee = async () => {
    await cook(2000);
    return '커피';
};
const myCookie = async () => {
    await cook(5000);
    return '쿠키';
};

async function asyncProcess() {
    const cake = await myCake();
    console.log(cake);
    const coffee = await myCoffee();
    console.log(coffee);
    const cookie = await myCookie();
    console.log(cookie);
}

asyncProcess();

///////////
// 비동기처리 //

setTimeout(()=> {
    console.log('5초 끝!')
}, 5000);

setTimeout(()=> {
    console.log('10초 끝!')
}, 10000);

function cook(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

const myCake = async () => {
    await cook(3000);
    return '케이크';
};

const myCoffee = async () => {
    await cook(2000);
    return '커피';
};
const myCookie = async () => {
    await cook(5000);
    return '쿠키';
};

async function promiseProcess() {
    const results = await Promise.all([myCake(), myCoffee(), myCookie()]);
    console.log(results);
}

promiseProcess();

// 질의응답
async function a() {
    console.log(1);
    setTimeout(()=> {
        console.log(2)
    }, 0);
    console.log(3)
}
a()
// 1, 3, 2

async function a() {
    console.log(1);
    await setTimeout(()=> {
        console.log(2)
    }, 1000);
    console.log(3)
}

a()
// 1, 3, 2

// why? await은 promise 앞에서만 사용
// await [[Promise 객체]] 의 형식

async 데이터가 다 올때까지 기다리고 있다

https://paullabworkspace.notion.site/JavaScript-f037c206e538471f9a9f1915b2139a60 책 참조

 

알아서 잘 딱 깔끔하고 센스있게 정리하는 JavaScript 핵심 개념

A new tool for teams & individuals that blends everyday work apps into one.

paullabworkspace.notion.site

DOM

DOM을 탐색해봅시다.

개행을 찾을 때

// body>h1{hello world}+p{hello}+div>h1{hello world}+p{hello}
document.body.childNodes
document.body.childNodes[1].textContent = 'hello hojun'
document.body.childNodes[3].childNodes[1]

// 해당하는 Id를 가진 요소에 접근하기
document.getElementById()

// 해당하는 모든 요소에 접근하기
document.getElementsByTagName();

// 해당하는 클래스를 가진 모든 요소에 접근하기
document.getElementsByClassName();

// css 선택자로 단일 요소에 접근하기
document.querySelector("selector");

// css 선택자로 여러 요소에 접근하기
document.querySelectorAll("selector");

// target 요소를 생성합니다.
document.createElement(target);

// target 텍스트를 생성합니다.
document.createTextNode(target);

// target 요소를 element의 자식으로 위치합니다.
element.appendChild(target);

// element의 target 자식 요소를 제거합니다.
element.removeChild(target);

+ Recent posts