1. 더보기버튼을 2번째 누르면 7,8,9번째 상품을 더 가져와서 html로 보여주십시오
https://codingapple1.github.io/js/more2.json여기로 GET요청하면 7,8,9번째 상품이 도착합니다.
힌트
유저가 더보기버튼을 몇 번 눌렀는지를 어디 기록해놔야
내가 버튼 누를 때마다 어디로 GET요청할 지 판단할 수 있겠군요.
그리고 그 다음 10,11,12번 상품은 없으니
버튼을 3번은 못누르게 버튼을 숨기거나 그래도 좋을듯요
1. 버튼이 몇번 눌렸는지 알 수 있는 방법
먼저 버튼 클릭에 대한 전역변수를 만들어준다.
let clickCount = 0;
이 이후에 버튼이 클릭되면 clickCount는 1씩 증가하게 되는 코드를 만들어보자
let clickCount = 0;
plusBtn.addEventListener("click", () => {
clickCount++;
console.log(clickCount);
getGoods();
});
이렇게 되면 버튼을 누를 때 마다 1씩 증가하게 되는 것을 콘솔에서 볼 수 있다.

2. 버튼이 1이면 4, 5, 6번째 상품을 보여주고 버튼이 2라면 7, 8, 9 상품을 보여주고 버튼이 3이라면 버튼을 숨기는 기능
let clickCount = 0;
plusBtn.addEventListener("click", () => {
clickCount++;
if (clickCount == 1) {
getGoods1();
} else if (clickCount == 2) {
getGoods2();
plusBtn.style.display = "none";
}
});
clickCount가 1이라면 getGoods1() 함수가 호출되면서 4, 5, 6번째 상품을 보여준다.
clickCount가 2이라면 getGoods2() 함수가 호출되면서 7, 8, 9번째 상품을 보여준 뒤
버튼을 숨긴다.
응용 1번문제에 대한 전체코드와 결과를 봐보자
const card = document.querySelector(".row");
const plusBtn = document.querySelector("#more");
let products = [
{ id: 0, price: 70000, title: "Blossom Dress" },
{ id: 1, price: 50000, title: "Springfield Shirt" },
{ id: 2, price: 60000, title: "Black Monastery" },
];
products.forEach((a, i) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${products[i].title}</h5>
<p>가격 : ${products[i].price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
let clickCount = 0;
plusBtn.addEventListener("click", () => {
clickCount++;
if (clickCount == 1) {
getGoods1();
} else if (clickCount == 2) {
getGoods2();
plusBtn.style.display = "none";
}
});
function getGoods1() {
fetch(`https://codingapple1.github.io/js/more1.json`)
.then((response) => response.json())
.then(function (data) {
data.forEach((a, i) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${data[i].title}</h5>
<p>가격 : ${data[i].price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
});
}
function getGoods2() {
fetch(`https://codingapple1.github.io/js/more2.json`)
.then((response) => response.json())
.then(function (data) {
data.forEach((a, i) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${data[i].title}</h5>
<p>가격 : ${data[i].price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
});
}

2. 유사한 코드가 발생하고 있습니다.
지금 코드를 잘 보면 forEach() 반복문을 2번 쓴 것 같은데
이 코드들이 매우 유사해보입니다.
함수나 그런걸로 축약해보는 연습도 해보면 좋을 것 같군요
힌트
함수로 축약할 때 안에 미지의 변수같은게 있으면 파라미터로 바꾸는게 좋다고 했는데
a, i 이런 변수는 이미 콜백함수에 의해 파라미터화가 되어있기 때문에 a, i는 신경안써도 될듯요
1. 반복되고 있는
template함수로 묶어두기let template = `<div class="col-sm-4"> <img src="https://via.placeholder.com/600" class="w-100"> <h5>${?[i].title}</h5> <p>가격 : ${?[i].price}</p> </div>`;카드 안의 상품이름, 가격을 넣어주는
template은 계속 반복되기 때문에 아래와 같이 함수로 정리해놓으면 좋다.
const card = document.querySelector(".row");
const plusBtn = document.querySelector("#more");
let products = [
{ id: 0, price: 70000, title: "Blossom Dress" },
{ id: 1, price: 50000, title: "Springfield Shirt" },
{ id: 2, price: 60000, title: "Black Monastery" },
];
function appendProducts(products) {
products.forEach((product) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${product.title}</h5>
<p>가격 : ${product.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
}
appendProducts(products);
1, 2, 3번 상품들이 appendProducts의 argument로 들어갔기 때문에 appendProducts의 parameter에는 1, 2, 3번 상품의 이름, 가격 데이터가 들어가 있다.
appendProducts가 호출됨으로서 처음에 1, 2, 3번 상품이 보여진다.
2.
appendProducts를 사용해 4, 5, 6, 7, 8, 9번 보여주기
let clickCount = 0;
plusBtn.addEventListener("click", () => {
clickCount++;
if (clickCount == 1) {
getGoods1();
} else if (clickCount == 2) {
getGoods2();
plusBtn.style.display = "none";
}
});
function getGoods1() {
fetch(`https://codingapple1.github.io/js/more1.json`)
.then((response) => response.json())
.then((data) => {
appendProducts(data);
});
}
function getGoods2() {
fetch(`https://codingapple1.github.io/js/more2.json`)
.then((response) => response.json())
.then((data) => {
appendProducts(data);
});
}
url의 정보안에는 4, 5, 6, 7, 8, 9번 상품들의 이름, 가격이 들어있기 때문에 정보를 가져온 뒤 JSON으로 바꾸어 준 뒤 그 정보들을 appendProducts의 argument로 들어가게 되면 1, 2, 3번 상품에서 설명한 방법과 똑같이 appendProducts의 parameter에 4, 5, 6번의 상품이 나오고 7, 8, 9번의 상품이 나오게 된다.

list.html
<!DOCTYPE html>
<html lang="en">
<head>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Level3</title>
</head>
<body>
<div class="container">
<div class="row"></div>
</div>
<div class="container">
<button class="btn btn-danger" id="more">더보기</button>
</div>
<script src="./list.js"></script>
</body>
</html>
list.js
const card = document.querySelector(".row");
const plusBtn = document.querySelector("#more");
let products = [
{ id: 0, price: 70000, title: "Blossom Dress" },
{ id: 1, price: 50000, title: "Springfield Shirt" },
{ id: 2, price: 60000, title: "Black Monastery" },
];
function appendProducts(products) {
products.forEach((product) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${product.title}</h5>
<p>가격 : ${product.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
}
appendProducts(products);
let clickCount = 0;
plusBtn.addEventListener("click", () => {
clickCount++;
if (clickCount == 1) {
getGoods1();
} else if (clickCount == 2) {
getGoods2();
plusBtn.style.display = "none";
}
});
function getGoods1() {
fetch(`https://codingapple1.github.io/js/more1.json`)
.then((response) => response.json())
.then((data) => {
appendProducts(data);
});
}
function getGoods2() {
fetch(`https://codingapple1.github.io/js/more2.json`)
.then((response) => response.json())
.then((data) => {
appendProducts(data);
});
}
오늘은 상품 가격순 정렬버튼과 기능을 만들어볼 것이다.
products라는 변수안에 있던걸 가격순으로 정렬하고products 변수에 있던 순서대로 카드 다시 생성하면array 정렬하는 법부터 알아보자!array 자료는 순서개념이 있다보니 정렬도 가능하다.
그냥 문자 가나다순으로 정렬하려면 .sort() 붙이면 되는데
숫자정렬은 이렇게 코드짜면 된다.
let arrayTest = [7,3,5,2,40];
arrayTest.sort(function(a, b){
return a - b
});
console.log(arrayTest);

이러면 숫자순으로 잘 출력된다.
근데 왜 저렇게 코드짜면 숫자순으로 정렬이 될까?
코드 동작원리 이런걸 알면 나중에 응용도 쉽게 가능하기 때문에 sort() 동작원리를 알아보자.
arrayTest.sort(function(a, b){
return a - b
});
a, b는 array 안의 자료들이다.return 오른쪽이 양수면 a를 오른쪽으로 정렬해준다.return 오른쪽이 음수면 b를 오른쪽으로 정렬해준다.array 안의 자료들을 계속 뽑아서 a, b에 넣어준다.a - b 저렇게 쓰면 숫자순 정렬이 되는 것이다.예를 들면 a, b가 7과 3일 경우 7 - 3 하면 4가 남는다.
4는 양수다. 그러면 7을 3보다 오른쪽으로 보내준다.
그래서 숫자 오름차순 (123순) 정렬이 완성되는 것이다.
그럼 array 안의 숫자 내림차순 (321순) 정렬은 어떻게 할까?
let arrayTest = [7,3,5,2,40];
arrayTest.sort(function(a, b){
return b - a
});
console.log(arrayTest);
이렇게 하면 return 오른쪽이 음수가 되기 때문에 내림차순 (321순)이 된다.
(참고)
sort 함수는 원본을 변형시켜버린다.
원본을 변형시켜버리면 나중에 원본으로 되돌아갈 수 없으니까 귀찮아질 수 있어서
array/object자료 조작시엔 원본을 따로 복사해두고 조작하는 경우도 있다.
우리가 계속 다루고 있는 products 변수는 array안에 object가 하나 있는데
let products = [
{ id: 0, price: 70000, title: "Blossom Dress" },
{ id: 1, price: 50000, title: "Springfield Shirt" },
{ id: 2, price: 60000, title: "Black Monastery" },
];
이렇게 생겼습니다.
안에 있는 { } 이것들을 가격 낮은순으로 정렬하려면 어떻게 코드를 짜야할까?
.sort() 동작원리를 기억해보자.
먼저 array 정렬코드를 만들어보자
products.sort(function(a, b){ return a - b });이렇게 되면
{ id: 0, price: 70000, title: "Blossom Dress" }-{ id: 1, price: 50000, title: "Springfield Shirt" }이거나 마찬가지이다.
우리는 가격에 대해 정렬을 하는 것이기 때문에 가격을 뽑아내면 될 것 같다.
object에서 price뽑아내기
products.sort(function (a, b) { return a.price - b.price; });가격만 뽑아내서 오름차순으로 바꿔주었다. 한번 콘솔에
products를 찍어보자
id순이였던 products가 price오름차순으로 바뀐 것을 볼 수 있다.
컴퓨터는 시키는 것만 하는 노예일 뿐이라
컴퓨터에게 뭘 기대하면 안된다. html도 새로 만들라고 코드짜면 된다.
이전에 만들었던 appendProducts함수에 정렬하는 코드를 넣는다면 될 것 같다.
function appendProducts(products) {
products.sort(function (a, b) {
return a.price - b.price;
});
products.forEach((product) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${product.title}</h5>
<p>가격 : ${product.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
}
이렇게 된다면 products에 상품정보가 올 때마다 상품의 price를 뽑아 정렬한 뒤 카드를 생성하는 순서가 될 것 같다.
실제로 가격순으로 잘 정렬이 되었는지 보자

성공!
array 자료에서 원하는 자료만 필터링하고 싶으면 filter 함수를 쓴다.
var arrayTest = [7,3,5,2,40];
var newArray = arrayTest.filter(function(a){
return 조건식
});
a라고 작명한건 array 에 있던 데이터를 뜻하고return 우측에 조건식을 넣으면 조건식에 맞는 a만 남겨준다.filter는 원본을 변형시키지 않는 고마운 함수기 때문에 새로운 변수에 담아써야한다.let arrayTest = [7,3,5,2,40];
let newArray = arrayTest.filter(function(a){
return a < 4
});
console.log(newArray)
예를 들어 여러 숫자가 있는데 그 중에 4 미만인 것만 남기고 싶으면 이렇게 쓰면 된다.
newArray 출력해보면 [2, 3] 들어있는 것을 볼 수 있다.

이런거 응용하면 쇼핑몰에서 "6만원 이하 상품만 보기" 이런 필터기능도 만들 수 있다.
products라는 자료에서 6만원 이하만 필터하고 새로 html 생성하면 될 것 같다.
array 안의 자료들을 전부 변형하려면 map 함수를 쓴다.
let arrayTest = [7,3,5,2,40];
let newArray = arrayTest.map(function(a){
return 수식같은거
});
a라고 작명한건 array 에 있던 데이터를 뜻하고return 우측에 변경될 수식같은걸 넣으면 된다.map은 원본을 변형시키지 않는 고마운 함수기 때문에 새로운 변수에 담아써야한다.let arrayTest = [7,3,5,2,40];
let newArray = arrayTest.map(function(a){
return a * 4
});
console.log(newArray)
예를 들어 array 안의 숫자들을 전부 4를 곱해주고 싶으면 이렇게 코드짜면 된다.
newArray 출력해보면 [28, 12, 20, 8, 160]이 들어있는 것을 볼 수 있다.

이런거 응용하면 쇼핑몰에서 "달러 -> 원화로 변환하기" 이런 기능도 만들 수 있을 것 같다.
array 안에 있는 숫자들을 달러가격이라고 생각해보자. 이걸 전부 원화가격으로 변경하고 싶으면 어떻게해야할까?
map 함수를 써서 1000얼마 곱해주면 될 것 같다.
1. "상품명 다나가순 정렬" 버튼과 기능을 만들어오십시오.
누르면 상품이 '다나가' 순으로 정렬되어야합니다.
우리는 아까 금액에 대한 오른차순으로 sort()함수를 사용하였다.
숙제는 상품명 순이니 현재 코드를 수정해야한다.
obejct에서 가격이 아니라 상품명 뽑아내기
function appendProducts(products) {
products.sort(function (a, b) {
return a.price - b.price;
});
products.forEach((product) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${product.title}</h5>
<p>가격 : ${product.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
}
위 코드에서 바꿀 것은 뭘까?
간단하게price가 아니라 title로 수정하면 될 것 같다.
문자 내림차순
문자의 오른차순과 내림차순은 숫자와 다른 방식이다.
아래 사이트를 참고해서 알아보니비교연산자 (< >)를 사용하면 된다.
배열 정렬 함수 sort
그러면 어떻게 수정하면 될까?
function appendProducts(products) {
products.sort(function (a, b) {
if (a.title < b.title) {
return 1;
} else {
return -1;
}
});
products.forEach((product) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${product.title}</h5>
<p>가격 : ${product.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
}
이렇게 수정하면 될 것 같다.
다 - 나 - 가 (Z - A) 순으로 바뀌었는지 확인해보자

가격순이 아니라 상품명 순으로 정렬된 것을 볼 수 있다.
2. "6만원 이하 상품보기" 버튼과 기능을 만들어오십시오.
누르면 6만원 이하 상품만 보여야합니다.
더보기버튼과 함께 동작하는지 안하는지는 신경안써도 됩니다.
이번에는 6만원 이하 버튼을 누르면 6만원 이하 카드만 보이도록 기능을 만들어보자
6만원 이하버튼 만들기<div class="container my-3"> <button class="btn btn-danger" id="filter">6만원이하</button> </div>
6만원 이하버튼에 대한 변수 생성const btnUnder = document.querySelector("#filter");
6만원 이하버튼 클릭시 6만원이하 카드를 생성하는 이벤트리스너 및 함수 생성
btnUnder.addEventListener("click", () => {
let newProduct = products.filter(function (a) {
return a.price <= 60000;
});
card.innerHTML = "";
newProduct.forEach((newProduct) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${newProduct.title}</h5>
<p>가격 : ${newProduct.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
});
6만원 이하 버튼을 누르게 되면 가격중에 6만원이하인 array들이 newProduct로 들어가게 된다.
후에 6만원 이하 상품들만 화면에 표시된다.

list.html
<!DOCTYPE html>
<html lang="en">
<head>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Level3</title>
</head>
<body>
<div class="container">
<div class="row"></div>
</div>
<div class="container">
<button class="btn btn-danger" id="more">더보기</button>
</div>
<div class="container my-3">
<button class="btn btn-danger" id="filter">6만원이하</button>
</div>
<script src="./list.js"></script>
</body>
</html>
list.js
const card = document.querySelector(".row");
const btnUnder = document.querySelector("#filter");
const plusBtn = document.querySelector("#more");
let products = [
{ id: 0, price: 70000, title: "Blossom Dress" },
{ id: 1, price: 50000, title: "Springfield Shirt" },
{ id: 2, price: 60000, title: "Black Monastery" },
];
function appendProducts(products) {
products.sort(function (a, b) {
if (a.title < b.title) {
return 1;
} else {
return -1;
}
});
card.innerHTML = "";
products.forEach((product) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${product.title}</h5>
<p>가격 : ${product.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
}
appendProducts(products);
let clickCount = 0;
plusBtn.addEventListener("click", () => {
clickCount++;
if (clickCount == 1) {
getGoods1();
} else if (clickCount == 2) {
getGoods2();
plusBtn.style.display = "none";
}
});
function getGoods1() {
fetch(`https://codingapple1.github.io/js/more1.json`)
.then((response) => response.json())
.then((data) => {
appendProducts(data);
});
}
function getGoods2() {
fetch(`https://codingapple1.github.io/js/more2.json`)
.then((response) => response.json())
.then((data) => {
appendProducts(data);
});
}
btnUnder.addEventListener("click", () => {
let newProduct = products.filter(function (a) {
return a.price <= 60000;
});
card.innerHTML = "";
newProduct.forEach((newProduct) => {
let template = `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${newProduct.title}</h5>
<p>가격 : ${newProduct.price}</p>
</div>`;
card.insertAdjacentHTML("beforeend", template);
});
});