[JS] DOM 문서 객체 모델

[JS] DOM 문서 객체 모델

이채현

DOM (문서 객체 모델…Document Object Model)

  • HTML ⇒ 문서
  • 문서를 조작하는 언어 ⇒ JavaScript
  • Document Object Model ← JavaScript가 DOM을 통해 HTML을 조작
  • DOM 내부에는 Node: HTML 요소 하나하나 전부를 지칭
    • Node는 Tree형태로 부모노드가 자식노드를, 자식노드가 그 자식노드를…
    • 각 Node에는 수 많은 Properties, Methods…가 존재

결론

  • HTML문서를 JavaScript로 모델링 한 것이 DOM
  • 인터페이스를 하나하나 자르면 단위가 Node이며, Node는 Tree구조로 이루어져있다.

Eg) ’li’ 태그를 뽑아보면 정보가아래처럼 수 많이 담겨있다.

자세히 보기
[JS] Algorithm - 자주 쓰이는 구문 정리(22.02.06)

[JS] Algorithm - 자주 쓰이는 구문 정리(22.02.06)

이채현

배열 중복값 개수 구하기

reduce()

reduce() 함수는, 배열의 값을 순회하면서 배열의 값을 특정 형태로 누적하는데 사용합니다.

1
2
3
4
5
6
7
8
9
10
const inputNum = [1, 1, 2, 3, 4, 2, 1];

const result1 = inputNum.reduce((obj, t) => (obj[t] = obj[t] ? obj[t] + 1 : 1, obj), {});

const result2 = inputNum.reduce((obj, t) => {
obj[t] = (obj[t] || 0) + 1;
return obj;
}, {});

// { '1': 3, '2': 2, '3': 1, '4': 1 }

forEach()

자세히 보기
[JS] ES6 - Promise

[JS] ES6 - Promise

이채현

Promises

async

자바스크립트는 순차적으로 처리되는게 아니라 한꺼번에 실행된다. ⇒ 자바스크립트의 비동기성(async)

이벤트 루프에서 비동기적으로 실행시킨다.

Promise

자세히 보기
[JS] ES6 - For

[JS] ES6 - For

이채현

For

forEach

1
2
3
4
5
6
7
8
9
const friends = ["me", "you", "nico"];

const addHeart = (current, index, array ) => ( console.log(current, index, array));

friends.forEach(addHeart);
// 파라미터 첫번째로 값을 주고 두번째로 인덱스를 주고 세번째로 현재 배열을 준다
// me 0 ["me", "you", "nico"]
// you 1 ["me", "you", "nico"]
// nico 2 ["me", "you", "nico"]

for…of

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for (const friend of friends) {
// 장점 1) const, let 뭐로 할건지 결정가능, forEach에서는 안됨
console.log(friend); // 모두다 출력됨
}

for (const char of "strings") {
console.log(char); // s t r i n g s 출력
}
// 장점 2) iterable한 모든것에서 작동한다

for (const friend of friends) {
if (friend === "steve") {
break;
} else {
console.log(char); // "me", "you", "nico" 이렇게만 출력
}
}
// 장점 3) 루프를 멈출수가있음!, 최고장점
자세히 보기
[JS] ES6 - Rest and Spread

[JS] ES6 - Rest and Spread

이채현

Rest and Spread

Spread

기본적으로 변수를 가져와 풀어 해쳐 전개해놓는 것.

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
/**
* Spread
*/
const friends = [1, 2, 3, 4];

console.log(friends); // [1, 2, 3, 4]
console.log(...friends); // 1 2 3 4

const family = ["a", "b", "c"];
console.log(friends + family); // 1,2,3,4a,b,c
console.log([friends, family]); // [ [ 1, 2, 3, 4 ], [ 'a', 'b', 'c' ] ]
console.log([...friends, ...family]); // [ 1, 2, 3, 4, 'a', 'b', 'c' ]
// spread를 통해 모든 요소를 담고 있는 하나의 object를 얻을 수 있다.
// array.push()를 이용하지 않고 값을 추가하여 새로운 객체를 만든다.
const newFriends = [...friends, 5, 6, 7];
console.log(newFriends); // [ 1, 2, 3, 4, 5, 6, 7]

const admin = {
username: "admin",
};
console.log({ ...admin, password: 123 }); // { username: 'admin', password: 123 }
// 조건식
// lastName을 입력받았을 때 값이 있을 때만 객체에 넣어주기
const lastName = prompt("Last name: ");
const person = {
username: "person",
age: 24,
...(lastName !== "" && { lastName }), // spread로 전개하려면 데이터가 object여야하므로, 중괄호로 감싸줌
// lastName: lastName !== "" ? lastName : undefined,
};
console.log(person);

Rest Parameters

자세히 보기
[JS] ES6 - Destructuring

[JS] ES6 - Destructuring

이채현

Destructuring

destructuring(비구조화)는 object나 array 등 안의 변수를 바깥으로 끄집어내는 것

Object Destructuring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Object Destructuring
*/
const settings = {
notifications: {
follow: true,
alerts: true,
unfollow: false,
},
color: {
theme: "dakr",
},
};

if (settingss.notifications.follow) {
// send email
}

// 기존에는 위와 같이 사용했다. 보기에 매우 불편하다.
// 만약 follow라는 값이 없느면 undefined오류가 발생할 것이다.

자세히 보기
[JS] ES6 - Array

[JS] ES6 - Array

이채현

Array

Array.of()

무엇이든 Array로 만들어준다.

1
2
3
4
// Array.of()
const alphabet = ["a", "b", "c", "d"];
const alphabet = Array.of("a", "b", "c", "d")const alphabet = Array.of("a", "b", "c", "d", 1, 2, 3);;
console.log(alphabet);

Array.from()

자세히 보기
[JS] ES6 - Strings

[JS] ES6 - Strings

이채현

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

자세히 보기
[JS] ES6 - Functions

[JS] ES6 - Functions

이채현

Functions

Arrow Functions

기존 함수의 모습을 개선했다.

기존 함수

1
2
3
4
5
6
7
8
9
10
11
function Hello() {
return "hi";
}
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map(function (name) {
return name + " ❤️";
});
console.log(hearts);
자세히 보기
[JS] ES6 - Variables

[JS] ES6 - Variables

이채현

Variables

Let and Const

var를 절대 사용하지 않고 let & const 사용하기

  • var를 쓰면 안되는 이유

    • var hoisting
      

      때문에…

      • var는 라이프사이클에서… 선언과 초기화를 동시에 한다.
      • global scope에 변수/함수를 선언할 경우 아무리 아래에 선언해도 제일 위로 올라간다. → 어디서 선언했든 상관없이, 항상 제일 위로 선언을 끌어올려준다.
      • block scope를 철저히 무시한다.

    ⇒ 이러한 유연성으로 작은 어플리케이션을 금방 만들 수 있지만, 프로젝트의 규모가 커지면서 나중에서는 선언하지도 않은 값이 멋대로 출력되거나, 개발자들간의 협업에서 여러가지 문제점이 생길 수 있다.

  • let은 선언과 초기화가 분리되어 그 사이에 TDZ가 생성되고, 접근할 경우 Reference Error가 발생한다.

  • const는 선언과 초기화가 동시에 진행되지만, 선언 이전에 TDZ가 생성되어 접근하면 Reference Error가 발생한다.

    Dead Zone

    temporal dead zone(TDZ)에 영향을 받는 구문은 크게..

    • const 변수
    • let 변수
    • class 구문
    • constructor() 내부의 super()
    • 기본 함수 매개변수

Block Scope

자세히 보기