Hyper Text Transfer Protocol (HTML 파일을 전송하는 프로토콜)
- html 전송 (주로)(HyperText Markup Language)
- text
- xml
...등등
let arr = [15, 35, 1, 20, 4, 9, 64]; arr.sort() //🌟 sort함수는 인자가없다면 0,1,2,3,4,5,(사전순)으로 정렬해준다 console.log(arr) //출력값: [1, 15, 20, 35, 4, 64, 9]
<script>
let arr = [15, 35, 1, 20, 4, 9, 64];
console.log(arr)
arr.sort(f1)
//인자- 1개(함수타입 f1)
console.log(arr)
function f1(a, b) {
return a - b
//오름차순정렬 하는 함수
}
function f2(a, b) {
return b - a
//내림차순정렬 하는 함수
}
e.g)
let abc = f1;
abc(5, 1)
🌟 함수에서 기억해야할 3가지
// 1. 인자 갯수타입
// 2. 동작하는지 정렬을 해준다
// 3. 함수 실행 결과의 리턴값
// 정렬된 새로운 함수
</script>
✏️ 일회성으로 만든다고하면 ...익명(이름없는)함수로, 중괄호{}
랑 return
생략가능 arrow function 사용가능
<script>
let arr = [15, 35, 1, 20, 4, 9, 64];
console.log(arr);
arr.sort((a, b) => a - b);
console.log(arr);
</script>
let arr2 = ['add', 'bg', 'crrr', 'dlll', 'eopopppp']
//해당 배열을 문자열의 길이가 긴 순서대로 정렬하고 싶다면?
🌟🌟 //a 에는 뒤에것이, b에는 앞에것이 들어온다.
//결과가 음수면 자리바꿈
arr2.sort((a, b) => b.length - a.length)
//해당 배열을 page수가 적은 애부터 정렬 (오름차순)
let arr3 = [
{ title: '대모험', page: 100 },
{ title: '뽀로로', page: 10 },
{ title: '홍길동전', page: 50 },
]
arr3.sort((a, b) => a.page - b.page)
//해당 배열을 title의 길이가 긴 순서대로 정렬하고 싶다면?
arr3.sort((a, b) => b.title.length - a.title.length)
let arr4 = [
{ title: '대모험', date: '2020-01-01' },
{ title: '뽀로로', date: '2022-01-02' },
{ title: '홍길동전', date: '2020-01-03' },
]
arr4.sort((a, b) => new Date(b.date) - new Date(a.date))
database.js
let tbl_posts = [ { id: 643, title: '내방병', content: '냉방 중인 사무실이나 집 등에서 오랜 시간 머물 때 나타나는 가벼운 감기, 두통, 근육통, 권태감, 소화불량 같은 임상 증상을 지칭하는 일반적인 용어', writerId: 'abc123@naver.com', createdAt: '2023-07-28 15:43', updatedAt: '2023-07-28 15:43', like: 3 }, { id: 644, title: '열사병', content: '고온 다습한 환경일 때 우리 몸이 체온조절중추의 기능을 상실해, 체온이 40℃ 이상 비정상적으로 올라가는 경우', writerId: 'test@naver.com', createdAt: '2023-07-30 15:43', updatedAt: '2023-07-30 15:43', like: 6 }, { id: 645, title: '저체온증', content: '신체가 추위에 노출되는 등의 환경적 요인이나 외상, 갑상선 기능 저하증과 같은 질환 등의 이유로 방어 기전이 억제되면서 정상 체온을 유지하지 못하고 체온이 35℃ 이하로 떨어진 경우', writerId: 'cdf99@naver.com', createdAt: '2023-06-28 15:43', updatedAt: '2023-06-28 15:43', like: 9 } ]
게시글 여러개를(목록) 가져오는 함수 (API 백엔드개발자가 만드는 함수) //page: 보고자 하는 페이지 //limit: 한 페이지당 게시물 갯수 //orderBy: // 'like' 좋아요 내림차순 정렬, ' // 'data' : 작성일 내림차순(최신순), (안썻을떄의 기본) // 'dateAsc':작성일 function fetchPosts(page, limit, orderBy) { //tbl_posts 는 15개의 객체가 들어있는 배열이다 if (orderBy === 'like') {// 좋아요순 정렬 tbl_posts.sort((a, b) => b.like - a.like); } else if (orderBy === 'dateAsc') {// 오래된순 tbl_posts.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)) } else {// 최신순 정렬 tbl_posts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) } // tbl_posts는 정렬이 잘 되었구나 // console.log(tbl_posts); // page : 1 2 page // limit : 10 10 m // 인덱스 : 0-9 10-19 (page-1)*limit <= < page*limit let res = tbl_posts.slice((page - 1) * limit, page * limit); // console.log(res); return { status: 200, data: { totalCount: tbl_posts.length, records: res } }; }
원본을 변형시키는 함수가 있고, 원본을 유지하는 함수가 있다
push
let arr= [10,20,30]; arr.push(50); //[10,20,30,50];
pop
let arr= [10,20,30]; arr.pop(30); //[10,20];
sort
let arr= [21, 10,30,90]; arr.sort(); //[10,21,30,90]
slice
let arr= [10,20,30,40]; arr.slice(0,3); //결과값은 [10,20,30] //arr 는 변하지 않는다. [10,20,30,40]
응용.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
div {
border: 3px solid black;
padding: 3px;
}
.table-row {
display: flex;
}
</style>
</head>
<body>
<div>
<div class="table-row">
<div style="width: 10%;" class="cell">번호</div>
<div style="width: 40%;" class="cell">제목</div>
<div style="width: 10%;" class="cell">작성자</div>
<div style="width: 10%;" class="cell">좋아요수</div>
<div style="width: 15%;" class="cell">작성일자</div>
<div style="width: 15%;" class="cell">수정일자</div>
</div>
<div class="table-row">
<div style="width: 10%;" class="cell">1</div>
<div style="width: 40%;" class="cell">ㄴㅇㄻㄴㄹ</div>
<div style="width: 10%;" class="cell">ㅁㄴㅇㄹㄹㄴㅇ</div>
<div style="width: 10%;" class="cell">5</div>
<div style="width: 15%;" class="cell">2022-11</div>
<div style="width: 15%;" class="cell">2023-13</div>
</div>
<div class="table-row">
<div style="width: 10%;" class="cell">1</div>
<div style="width: 40%;" class="cell">ㄴㅇㄻㄴㄹ</div>
<div style="width: 10%;" class="cell">ㅁㄴㅇㄹㄹㄴㅇ</div>
<div style="width: 10%;" class="cell">5</div>
<div style="width: 15%;" class="cell">2022-11</div>
<div style="width: 15%;" class="cell">2023-13</div>
</div>
<div class="table-row">
<div style="width: 10%;" class="cell">1</div>
<div style="width: 40%;" class="cell">ㄴㅇㄻㄴㄹ</div>
<div style="width: 10%;" class="cell">ㅁㄴㅇㄹㄹㄴㅇ</div>
<div style="width: 10%;" class="cell">5</div>
<div style="width: 15%;" class="cell">2022-11</div>
<div style="width: 15%;" class="cell">2023-13</div>
</div>
<div class="table-row">
<div style="width: 10%;" class="cell">1</div>
<div style="width: 40%;" class="cell">ㄴㅇㄻㄴㄹ</div>
<div style="width: 10%;" class="cell">ㅁㄴㅇㄹㄹㄴㅇ</div>
<div style="width: 10%;" class="cell">5</div>
<div style="width: 15%;" class="cell">2022-11</div>
<div style="width: 15%;" class="cell">2023-13</div>
</div>
<div class="table-row">
<div style="width: 10%;" class="cell">1</div>
<div style="width: 40%;" class="cell">ㄴㅇㄻㄴㄹ</div>
<div style="width: 10%;" class="cell">ㅁㄴㅇㄹㄹㄴㅇ</div>
<div style="width: 10%;" class="cell">5</div>
<div style="width: 15%;" class="cell">2022-11</div>
<div style="width: 15%;" class="cell">2023-13</div>
</div>
</div>
<div id="button-wrap"></div>
<script src="database.js"></script>
</body>
</html>
database.js
let res = fetchPosts(1, 5, 'date');
// 총필요한 페이지 :
// 전체게시글 20, 한페이지당 5 --> 1, 2, 3, 4
// 전체게시글 16, 한페이지당 5 --> 1, 2, 3, 4
// 전체게시글 15, 한페이지당 5 --> 1, 2, 3
let totalPage = Math.ceil( res.data.totalCount / 5);
let btnWrap = document.querySelector('#button-wrap');
for(let i = 0; i < totalPage; i++){
let newBtn = document.createElement('button');
newBtn.textContent = i+1;
btnWrap.appendChild(newBtn);
}
이러한 반복적
인 코드를 어떻게 바꿀수있을까?
일단은, class
를 준다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
div {
border: 3px solid black;
padding: 3px;
}
.table-row {
display: flex;
}
.cell10 {
width: 10%;
}
.cell40 {
width: 40%;
}
.cell15 {
width: 15%;
}
</style>
</head>
<body>
<div id="table">
<div class="table-row">
<div class="cell cell10">번호</div>
<div class="cell cell40">제목</div>
<div class="cell cell10">작성자</div>
<div class="cell cell10">좋아요수</div>
<div class="cell cell15">작성일자</div>
<div class="cell cell15">수정일자</div>
</div>
</div>
<div id="button-wrap"></div>
<script src="database.js"></script>
</body>
</html>
database.js
// 한 페이지 당 보여줄 게시물의 갯수
let limit = 2;
//특정 페이지의 게시물을 그려주는 함수
const getPosts = (page) => {
// db에서 내가 필요한 게시물 2개를 가져온다
let res = fetchPosts(page, limit, 'date');
// tableDiv에 보여지고 있는 두개의 게시물 행을 삭제를 한다.
let tableDiv = document.querySelector('#table');
// tableDiv.children 에는 tableDiv의 자식들이 들어있다
// [ 제목행, 게시물행, 게시물행]
// [ 제목행, 게시물행]
// [ 제목행]
let cnt = tableDiv.children.length - 1; // 2
while (tableDiv.children.length > 1) {
tableDiv.removeChild(tableDiv.children[cnt]);
cnt--; // 0
}
for (let i = 0; i < res.data.records.length; i++) {
let newRow = document.createElement('div');
newRow.className = "table-row";
// 첫번째 반복때는 i : 0
// 두번째 반복때는 i : 1
//res.data.records[i].id
// cell1 div 만들기
let cell1 = document.createElement('div');
cell1.className = 'cell cell10';
cell1.textContent = res.data.records[i].id;
newRow.appendChild(cell1);
// cell2 만들기
let cell2 = document.createElement('div');
cell2.className = 'cell cell40';
cell2.textContent = res.data.records[i].title;
newRow.appendChild(cell2);
// cell3 만들기
let cell3 = document.createElement('div');
cell3.className = 'cell cell10';
cell3.textContent = res.data.records[i].writerId;
newRow.appendChild(cell3);
// cell4 만들기
let cell4 = document.createElement('div');
cell4.className = 'cell cell10';
cell4.textContent = res.data.records[i].like;
newRow.appendChild(cell4);
// cell5 만들기
let cell5 = document.createElement('div');
cell5.className = 'cell cell15';
cell5.textContent = res.data.records[i].createdAt;
newRow.appendChild(cell5);
// cell6 만들기
let cell6 = document.createElement('div');
cell6.className = 'cell cell15';
cell6.textContent = res.data.records[i].updatedAt;
newRow.appendChild(cell6);
// id가 table인 div를 가져와서
// div 추가하기
let tableDiv = document.querySelector('#table');
tableDiv.appendChild(newRow);
}
}
let res = fetchPosts(1, limit, 'date');
console.log(res);
// 총필요한 페이지 :
// 전체게시글 20, 한페이지당 5 --> 1, 2, 3, 4
// 전체게시글 16, 한페이지당 5 --> 1, 2, 3, 4
// 전체게시글 15, 한페이지당 5 --> 1, 2, 3
let totalPage = Math.ceil(res.data.totalCount / limit);
let btnWrap = document.querySelector('#button-wrap');
for (let i = 0; i < totalPage; i++) {
let newBtn = document.createElement('button');
newBtn.textContent = i + 1;
newBtn.onclick = () => {
getPosts(i + 1);
}
btnWrap.appendChild(newBtn);
}