자바스크립트 (2)
포스트
취소

자바스크립트 (2)

조건문과 반복문

  • 다른 언어랑 별 차이 없음 아는대로 쓰면 됨
  • if - else if - else
  • for (let i = 0; i< n; i++) {}
  • while (flag) {}

함수

  • 함수를 그냥 정의할 수도 있고
  • 변수에 대입+정의할 수도 있고
    • 대입+정의문을 일부 생략할 수도 있음
  • 정의된 이름들의 뒤에 괄호를 붙이면 호출할 수 있다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function 함수이름(전달받을값) { // 함수 선언식
    // 실행할 코드
    return 1;
}

const 변수명 = function(전달받을값) { // 함수 표현식
    // 실행할 코드
    return 2;
}

const 화살표함수 = () => { // 화살표 함수
    // 실행할 코드
    return 3;
}
  • 콜백 함수: 다른 함수의 인자로 전달되어 그 함수 내에서 호출되는 함수
1
2
3
4
5
6
7
8
9
10
function greet(name, callback) {
    console.log(`안녕하세요, ${name}님!`);
    callback(); // 전달받은 콜백 함수 실행
}

function sayBye () {
    console.log("안녕히 가세요!");
}

greet("세모덕", sayBye);
  • 이벤트 핸들러는 사실 콜백 함수의 일종이다. 콜백 함수 중에 ‘이벤트 발생 시 호출됨’이라는 용도를 가진 것들을 구분하여 부르는 이름.
    • 이벤트 리스너: 이벤트 핸들러를 호출해주는 객체
  • HTML 버튼 클릭 시 함수 호출하기
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>색상바꾸기</title>
    <style>
        div {
            width:100px;
            height:100px;
            border : 1px solid black;
        }
    </style>
    <script>
        const colors = ['red', 'orange', 'yellow']
        let idx = -1;
        document.querySelector('input').addEventListener('click', function () {
            idx++
            if (idx >= colors.length) {
                idx = 0;
            }
            document.querySelector('div').style.background = colors[idx];
            })
    </script>
</head>
<body>
    <input type="button" value="색상바꾸기">
    <div></div>
</body>
</html>

비동기 처리

  • 비동기 처리는 코드가 쓰인 순서대로 실행하지 않는다. 코드가 어느 라인에 있든 그냥 때 되면 하는거임.
1
2
3
4
5
6
7
console.log('1')

setTimeout(() => { console.log('2000') }, 1000);

setTimeout(() => { console.log('0') }, 0);

console.log('3')
  • 예시: axios와 비동기 통신하기
1
2
3
4
5
6
7
8
9
10
11
12
const url = 'https://jsonplaceholder.typicode.com/todos'

async function getData() {
    const result = await axios.get(url);
    const resData = result.data;

    const res = resData.filter(data => data.completed === false).filter(data => data.userId % 2 === 0).filter(data => data.title.length >=10);

    console.log(res);
}

getData();
이 기사는 저작권자의 CC BY-NC-ND 4.0 라이센스를 따릅니다.

AI 하네스 엔지니어링

Vue.js (3)