<script>
var 출석부 = ['흥민', '흥민', '영희', '철수', '재석'];
function find(name) {
var found = false;
출석부.forEach(function(nameList){
if(name === nameList){
found = true;
}
});
if(found){
console.log("있음");
} else {
console.log("없음");
}
}
find("흥민"); // 있음
find("메롱"); // 없음
</script>
<script>
// 1번 다른 방법
var 출석부 = ['흥민', '흥민', '영희', '철수', '재석'];
function find(name){
for(let i=0; i<출석부.length; i++){
if(name == 출석부[i]){
console.log("있음");
return;
}
} console.log("없음");
}
find("흥민"); // 있음
find("메롱"); // 없음
</script>
<script>
// 2번 문제 : 구구단 출력
for(let i=2; i<=9; i++){
for(let j=1; j<9; j++){
console.log(`${i} * ${j} = ${i*j}`);
}
}
</script>
<script>
// 2번 문제 : 구구단 출력
for(let i=2; i<=9; i++){
for(let j=1; j<9; j++){
console.log(`${i} * ${j} = ${i*j}`);
}
}
</script>
<script>
function 계산기 (array, b) {
var total = 0;
var avg;
for(let i=0; i<array.length; i++){
total += array[i];
}
avg = total/array.length;
if (avg < b){
console.log(`지난 평균점수보다 ${b-avg}점 올랐습니다`);
} else {
console.log(`지난 평균점수보다 ${avg-b}점 떨어졌습니다`)
}
}
계산기 ([10, 20, 30, 40, 50], 40); //지난 평균점수보다 10점 올랐습니다
계산기 ([40, 40, 40], 20); //지난 평균점수보다 20점 떨어졌습니다
</script>
<form action="요청할url" method="post"> 태그 이용하면 폼 전송되었을 때 POST 요청 날려줌AJAX는 새로고침 없이 데이터를 주고받을 수 있게 도와주는 간단한 브라우저 기능$.get('https://codingapple1.github.io/hello.txt');
.done 또는 .then 뒤의 콜백함수 속 파라미터 안에 들어있음jQuery의 $.get()은 JSON으로 자료를 받아오면 알아서 array/object 자료로 바꿔줌
$.get('https://codingapple1.github.io/hello.txt').done(function(data){
console.log(data); //'안녕하세요 반갑습니다요.'
}).fail(function(){
console.log("ajax 요청 실패");
});
$.get('https://codingapple1.github.io/price.json').done(function(data){
console.log(data); // {price: 5000}
console.log(data.price); // 5000
}).fail(function(){
console.log("ajax 요청 실패");
});
$.post('https://codingapple1.github.io/hello.txt', {name:"kim"}).done(function(data){
console.log(data);
});
기본함수
fetch()는 JSON으로 자료를 받아오면 알아서 array/object 자료로 바꿔주지 않음
→fetch()로 가져온 결과를 array/object로 바꾸고 싶으면 res.json() 추가해야함
fetch('https://codingapple1.github.io/price.json')
.then(res => res.json()) // 받아온 JSON을 Object로 바꿔주는 기능
.then(data => {
console.log(data);
console.log(data.price);
}).catch(error => {
console.log(error);
});
<div class="container">
<div class="row">
<!-- 여기에 카드 3개 만들기
<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>Card title</h5>
<p>가격 : 70000</p>
</div>
-->
</div>
</div>
<script>
var products = [
{ id : 0, price : 70000, title : 'Blossom Dress' },
{ id : 1, price : 50000, title : 'Springfield Shirt' },
{ id : 2, price : 60000, title : 'Black Monastery' }
];
products.forEach((item, i) => { // 기본 카드
var card =
`<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${item.title}</h5>
<p>가격 : ${products[i].price}</p>
</div>`;
$('.row').append(card);
});
</script>
<!--상품 더 보기 버튼-->
<div class="container">
<button class="btn btn-danger" id="newProdcuts">더보기</button>
</div>
<script>
var cnt = 1;
$('#newProdcuts').click(function(){
if(cnt == 1){
$.get('https://codingapple1.github.io/js/more1.json')
.done((data) => {
console.log(data);
data.forEach((item, i) => {
var card =
`<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${data[i].title}</h5>
<p>가격 : ${item.price}</p>
</div>`;
$('.row').append(card);
});
cnt++ ;
}).fail(function(){
console.log(error);
});
} else if (cnt == 2){
$.get('https://codingapple1.github.io/js/more2.json')
.done((data)=>{
console.log(data);
data.forEach((item) => {
var card
= `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${item.title}</h5>
<p>가격 : ${item.price}</p>
</div>`;
$('.row').append(card);
$('#newProdcuts').hide();
});
return;
}).fail(function(){
console.log(error);
});
}
});
</script>
function createCard(item){
return `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${item.title}</h5>
<p>가격 : ${item.price}</p>
</div>`;
}
var cnt = $(this).data('cnt') || 1
: jQuery를 사용해 클릭 횟수 추적, 기본값 1로 설정
$(this)는 현재 클릭된 요소인 $('#newProducts')
data('cnt')메서드를 사용해 해당 요소의 data-cnt 속성값 가져옴
$('#newProdcuts').data('cnt', 2);에서 cnt를 2로 업데이트
<script>
var products = [
{ id : 0, price : 70000, title : 'Blossom Dress' },
{ id : 1, price : 50000, title : 'Springfield Shirt' },
{ id : 2, price : 60000, title : 'Black Monastery' }
];
function createCard(item){
return `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${item.title}</h5>
<p>가격 : ${item.price}</p>
</div>`;
}
products.forEach((item, i) => {
var card = createCard(item);
$('.row').append(card);
});
$('#newProdcuts').click(function(){
var cnt = $(this).data('cnt') || 1;
if(cnt == 1){
$.get('https://codingapple1.github.io/js/more1.json')
.done((data) => {
console.log(data);
data.forEach((item, i) => {
var card = createCard(item);
$('.row').append(card);
});
$('#newProdcuts').data('cnt', 2);
}).fail(function(){
console.log(error);
});
} else if (cnt == 2){
$.get('https://codingapple1.github.io/js/more2.json')
.done((data)=>{
console.log(data);
data.forEach((item) => {
var card = createCard(item);
$('.row').append(card);
});
$('#newProdcuts').hide();
}).fail(function(){
console.log(error);
});
}
});
</script>
-ex ) a, b가 7과 3일 경우 7 - 3 하면 → 양수 4
→ 7을 3보다 오른쪽으로 보냄
var array = [7, 3, 5, 10];
var array2 = ['a', '가', 'c', '바'];
// 오름차순 정렬
array.sort(function(a,b){
return a-b;
});
console.log(array);
// 내림차순 정렬
array.sort(function(a,b){
return b-a;
});
console.log(array);
// 문자 오름차순 정렬
array2.sort()
console.log(array2);
// 문자 내림차순 정렬
array2.sort(function(a, b){
return a < b ? 1 : -1;
});
console.log(array2);
var products = [
{ id : 0, price : 70000, title : 'Blossom Dress' },
{ id : 1, price : 50000, title : 'Springfield Shirt' },
{ id : 2, price : 60000, title : 'Black Monastery' }
];
products.sort(function(a, b){
return a - b
});
products.sort(function(a, b){
return a.price - b.price // object 안에 있는 가격끼리 빼기
});
console.log(products);
var allProducts = [...products];... 스프레드 연산자concat : 배열에 다른 배열이나 값들을 합침
allProducts = allProducts.concat(data);
: concat을 사용해 초기 제품 목록이 있는 allProcucts 배열에 data 배열을 합쳐서 새로운 배열 반환
→ 합친 배열을 다시 allProducts에 할당
<script>
var products = [
{ id : 0, price : 70000, title : 'Blossom Dress' },
{ id : 1, price : 50000, title : 'Springfield Shirt' },
{ id : 2, price : 60000, title : 'Black Monastery' }
];
// 초기 제품을 포함하는 모든 제품 목록
var allProducts = [...products];
// 카드 생성
function createCard(item){
return `<div class="col-sm-4">
<img src="https://via.placeholder.com/600" class="w-100">
<h5>${item.title}</h5>
<p>가격 : ${item.price}</p>
</div>`;
}
// 제품 표시 : 기존 products를 지우고 제품 표시
function showProducts(products) {
$('.row').html('');
products.forEach((item) => {
var card = createCard(item);
$('.row').append(card);
});
}
// 초기 제품 표시
showProducts(products);
// 더보기 버튼 이벤트 핸들러
$('#newProdcuts').click(function(){
var cnt = $(this).data('cnt') || 1;
if(cnt == 1){
$.get('https://codingapple1.github.io/js/more1.json')
.done((data) => {
console.log(data);
allProducts = allProducts.concat(data);
showProducts(allProducts);
$('#newProdcuts').data('cnt', 2);
}).fail(function(){
console.log(error);
});
} else if (cnt == 2){
$.get('https://codingapple1.github.io/js/more2.json')
.done((data)=>{
console.log(data);
allProducts = allProducts.concat(data);
showProducts(allProducts);
$('#newProdcuts').hide();
}).fail(function(){
console.log(error);
});
}
});
// 가격 순 정렬 버튼 이벤트 핸들러
$('#price').on('click', function(){
allProducts.sort(function(a, b){
return a.price - b.price;
});
console.log(allProducts);
showProducts(allProducts);
});
</script>
</body>
</html>
// 가나다 순 정렬버튼
$('#sort1').on('click', function(){
allProducts.sort((a, b) => {
return a.title > b.title ? 1: -1;
});
console.log(allProducts);
showProducts(allProducts);
});
// 다나가 순 정렬버튼
$('#sort2').click(function(){
allProducts.sort((a, b) => {
return a.title < b.title ? 1: -1;
});
showProducts(allProducts);
});
var arr = [7, 3,2, 5, 40];
var filterArr = arr.filter(function(item) {
return item <= 5;
});
console.log(filterArr); // [3, 2, 5]
// 6만원 이하
$('#filter').click(() => {
var sixUnder = allProducts.filter((item)=>{
return item.price <= 60000
});
console.log(sixUnder);
showProducts(sixUnder);
});
// 6만원 이하2 (allow로 더 간편하게)
// 함수 { } 안에 return 한 줄 밖에 없으면 중괄호와 return 동시에 생략가능
$('#filter').click(() => {
var sixUnder = allProducts.filter((item) => item.price <= 60000);
showProducts(sixUnder);
});
<div class="container my-3">
<div class="input-group mb-3">
<input type="text" id="titleSearch" class="form-control" placeholder="제품명 검색" style="width: 20%;">
<button class="btn btn-primary" id="search" style="margin-right:10px">검색</button>
<input type="number" id="priceInput" class="form-control" placeholder="가격 입력" style="width: 20%;">
<button class="btn btn-primary" id="filterPrice">가격으로 필터</button>
</div>
</div>
<script>
$('#filterPrice').click(() => {
var priceInput = $('#priceInput').val().trim();
if(price === '' ){
alert("가격을 입력하세요");
return;
}
var filterPriceProduct = allProducts.filter((item) => {
return item.price <= parseInt(priceInput);
})
showProducts(filterPriceProduct);
})
</script>
var arr = [7, 3,2, 5, 40];
var mapArr = arr.map((item) => {
return item * 5;
});
console.log(mapArr); // [35, 15, 10, 25, 200]
{ ...item, price: ... }{(item.price / 1200).toFixed(2)} $('#map').click(() => {
var toDollar = allProducts.map((item) => {
return { ...item, price: `$${(item.price / 1200).toFixed(2)}` };
});
console.log(toDollar);
showProducts(toDollar);
});
$('#search').click(()=>{
var searchTitle = $('#titleSearch').val().trim();
if(searchTitle === ''){
alert('검색어를 입력하세요.');
return;
}
var searchResult = allProducts.filter((item)=>{
return item.title.toLowerCase().includes(searchTitle.toLowerCase());
})
showProducts(searchResult);
});
// 원래 순서로
$('#reset').click(function(){
allProducts = [...products]; // 초기 데이터로
showProducts(allProducts);
});