-
데이터 바인딩 연습과 sort,map,filter등 분류 함수JAVASCRIPT 2022. 2. 15. 01:54
데이터 바인딩 연습을 하기 위해서
<div class="card-group container"> <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">Card title</h5> <p>가격 : <span class="price">70000</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">Card title</h5> <p>가격 : <span class="price">70000</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">Card title</h5> <p>가격 : <span class="price">70000</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> </div>
이런 세개의 박스 컨테이너 html을 짠 후,
여기에 자바스크립트에 있는 데이터를 가져다 박아넣을 수 있다.
var products = [ { id : 0, price : 70000, title : 'Blossom Dress' }, { id : 1, price : 50000, title : 'Springfield Shirt' }, { id : 2, price : 60000, title : 'Black Monastery' } ]; $('.title').eq(0).html(products[0].title); $('.price').eq(0).html(products[0].price); $('.title').eq(1).html(products[1].title); $('.price').eq(1).html(products[1].price); $('.title').eq(2).html(products[2].title); $('.price').eq(2).html(products[2].price);
위처럼 products라는 데이터를 가져오는 것은 ajax를 사용하면 되는데, ajax는 나중에 배워보고 저번에 한 것처럼, 어레이[순서].objects의키 이런식으로 배열을 만질 수 있다.
이제 가격순정렬 버튼을 만들어 가격순으로 정렬해보자
<div class="container my-5"> <button id="sort-btn1" class="btn btn-danger">가격순정렬</button> </div>
가격순정렬 버튼을 누르면 가격별로 정렬하기 위해선 sort라는 문법을 알아야 한다.
sort는 기본적으로 문자정렬이다. 그래서
//다음과 같이 쓰면 문자정렬이 된다. 어레이이름.sort() //숫자 정렬을 하려면 다음과 같이 써야한다. 어레이이름.sort(function(a,b) { return a - b; });
숫자 정렬을 하는 원리는 a,b는 어레이 안의 데이터이고 빼서,
양수가 나오면 b를 왼쪽으로 보내고 a를 오른쪽으로 보낸다. (+면 b - a 순서)
음수가 나오면 b를 오른쪽으로 보내고 a를 왼쪽으로 보낸다. (-면 a - b 순서) 가 된다.
그래서 오름차순은 a-b 내림차순은 b-a를 return에 적어준다.
따라서 가격순 정렬에 적용해보면
$('#sort-btn1').on('click', function() { products.sort(function(a,b) { return a.price - b.price; }); //여기까진 그저 어레이를 정렬이고, 이 후에 데이터 바인딩(html)을 다시 조작해 라고 명령해야함 $('.title').eq(0).html(products[0].title); $('.price').eq(0).html(products[0].price); $('.title').eq(1).html(products[1].title); $('.price').eq(1).html(products[1].price); $('.title').eq(2).html(products[2].title); $('.price').eq(2).html(products[2].price); });
이런 식으로, 적어주면 가격순 정렬도 만들 수 있다.
추가로, map과 filter를 배워보자.
//내가 원하는 필터를 할 때 var 뉴어레이 = 어레이.filter(function(a) { return 조건식 }); //어레이 전부에 뭐 해주고 싶을 때 (쇼핑몰에 가격변환 달러로 변환 기능 이럴때 쓰임) var 뉴어레이 = 어레이.map(function(a) { return 해줄것(ex. a * 2) }); //filter와 map둘다 기본 어레이를 변형시키지 않아 변수에 담아서 사용해야 함 //sort는 기본 어레이 변형시킴
연습으로 가나다 정렬 버튼을 만들어보자
<div class="container my-5"> <button id="sort-btn2" class="btn btn-danger">가나다정렬</button> </div>
$('#sort-btn2').on('click', function() { products.sort(function (a,b) { if (a.title < b.title) { return -1 } else { return 1 } }); $('.title').eq(0).html(products[0].title); $('.price').eq(0).html(products[0].price); $('.title').eq(1).html(products[1].title); $('.price').eq(1).html(products[1].price); $('.title').eq(2).html(products[2].title); $('.price').eq(2).html(products[2].price); });
위 처럼 써줄 수 있다. 문자 비교는 아스키코드를 기반으로 해 ㄱ보다 ㄴ이 크고 a보다 b가 큰 특성을 이용해서
a의 제목보다 b의 제목이 크면 (a 가 ㄱ, b 가 ㄴ) 음수를 반환해 a - b순서가 나오게 하고,
a의 제목이 b의 제목보다 크면 (a 가 ㄴ, b 가 ㄱ) 양수를 반환해 b - a순서가 나오게 한다.
6만원이라는 값을 input태그로 받아서 60000만원 이하 정렬도 만들어보자
<div class="container my-5"> <button id="sort-btn3" class="btn btn-danger">가격이하정렬</button> <input type="text" class="sort-btn3-input"> </div>
위 처럼 input태그도 만들어주고
$('#sort-btn3').on('click', function() { var newProducts = products.filter(function(a) { return a.price <= $('.sort-btn3-input').val() }); $('.card-group').html(''); newProducts.forEach(function(a) { var template = ` <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">${a.title}</h5> <p>가격 : <span class="price">${a.price}</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> `; $('.card-group').append(template); }); });
버튼을 클릭하면 filter기능을 이용해서 newProducts라는 변수에 a(어레이의 자료).price가 버튼의input.val() 값보다 작거나 같은 데이터를 모아서 담고, 그대로 정렬하면 기존값과 같이 정렬되기에 먼저, html을 비워주고 동적으로 정렬시킨다.
정렬할 땐 forEach반복문을 이용해 newProducts의 개수만큼 반복을 하며, title엔 a.title, price엔 a.price가 들어가게 한 후, 만든 template를 append해주면 정렬 끝이다.
이와 비슷하게, 원래대로 만드는 버튼을 만들어보자
<div class="container my-5"> <button id="sort-btn4" class="btn btn-danger">원래대로</button> </div>
원래대로 버튼을 만들땐 원래 있던 어레이의 사본을 만들어서 사용하는게 낫다고 한다. 정렬을 하다보면 원래의 어레이를 훼손시키는 경우가 있기에 미리 사본을 만드는 것이다.
var products2 = [...products]; //사본 만들때 //var 어레이 =[1,2,3] //var 어레이2 = 어레이 이건 사본이 아니라 값을 공유해주세요임 //따라서 var 어레이2 = [...어레이]이렇게 써야함 $('#sort-btn4').on('click', function() { $('.card-group').html(''); products2.forEach(function(a) { var template = ` <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">${a.title}</h5> <p>가격 : <span class="price">${a.price}</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> `; $('.card-group').append(template); }); });
위처럼, 사본을 만들어주고 버튼을 누르면 먼저, html을 다 지우주고 사본의 데이터 수 만큼 동적으로 template를 만들어 append해주면 된다.
마지막으로, 쇼핑몰 상품이 많아지면 그때마다 html을 추가해 줄 수 없으니 반복문을 이용해서 추가해보자
<div class="card-group container"> <!-- <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">Card title</h5> <p>가격 : <span class="price">70000</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">Card title</h5> <p>가격 : <span class="price">70000</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">Card title</h5> <p>가격 : <span class="price">70000</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> --> </div>
이렇게 안의 내용을 주석처리 한 후,
window.onload = function() { products.forEach(function(a) { var template = ` <div class="card"> <img src="https://via.placeholder.com/600"> <div class="card-body"> <h5 class="title">${a.title}</h5> <p>가격 : <span class="price">${a.price}</span></p> <button class="btn btn-danger">주문하기</button> </div> </div> `; $('.card-group').append(template); }); };
window.onload는 window(우리가 보고있는 창)이 onload(새로고침)될 때 라는 뜻이다. 이럴때 products라는 배열에 들어있는 수 만큼 반복을 하는데, 동적으로 html을 넣는 것을 반복해주세요 라고 코드를 짜주면 된다.
'JAVASCRIPT' 카테고리의 다른 글
ajax (2) 2022.02.17 DOM의 개념과 이벤트리스너 ready, load (2) 2022.02.16 인터렉티브 폼 (input,change이벤트, HTML동적생성, forEach반복문) (2) 2022.02.11 array와 object 자료형, 데이터바인딩 (2) 2022.02.10 이벤트 버블링 응용과 dataset 으로 탭기능 만들기 (2) 2022.02.10