JS/[codeit] jQuery (완)

[ codeit ] jQuery - jQuery 시작하기(2)

web_seul 2021. 6. 8. 21:52
반응형

 과제로 워밍업 

1강. JavaScript의 기능들

2강. Math 정리노트

절대값(Absolute Number) : Math.abs(x)

console.log(Math.abs(-10)); //10
console.log(Math.abs(10)); //10

 

최댓값(Maximum) : Math.max(a, b, c)

console.log(Math.max(2, -1, 0); //2

 

최솟값(Minimum) : Math.min(a, b, c)

console.log(Math.max(2, -1, 0); //-1

 

거듭제곱(Exponentiation) : Math.pow(x, y)

console.log(Math.pow(2, 3); //8

 

제곱근(Square Root) : Math.sqrt(x)

console.log(Math.sqrt(9); //3

 

반올림(Round) : Math.round(x)

console.log(Math.round(2.3); //2

 

버림과 올림(Floor and Ceil) : Math.floor(x) , Math.ceil(x)

console.log(Math.floor(2.3); //2
console.log(Math.ceil(2.3); //3

 

난수(Random) : Math.random(x)

console.log(Math.random(); //0.2132

 

3강. String 정리노트

문자열의 길이 : str.length

var str = 'Codeit';
console.log(str.length); //6

 

특정 인덱스의 문자 받아오기 : str.charAt(index) = str[index]

var str = 'Codeit';
console.log(str.charAt(2)); //d

 

문자열 안에서 다른 문자열 검색 : str.indexOf(searchValue)

1) 포함된 경우, 해당 문자열의 인덱스 리턴

2) 포함되지 않은 경우, -1리턴

3) 여러번 포함된 경우, 첫 인덱스 리턴

var str = 'Hello World!';

console.log(str.indexOf('e')); //1
console.log(str.indexOf('z')); //-1
console.log(str.indexOf('ello')); //1
console.log(str.indexOf('o')); //4

 

마지막 인덱스 찾기 : lastIndexOf(searchValue)

var str = 'Hello World!';

console.log(str.indexOf('o')); //4
console.log(str.lastIndexOf('o')); //7    ...? 띄어쓰기도 카운트?

 

대문자 변환 : str.toUpperCase()

var str = 'Codeit';
console.log(str.toUpperCase()); //CODEIT

 

소문자 변환 : str.toLowerCase()

var str = 'Codeit';
console.log(str.toLowerCase()); //codeit

 

시작지점과 끝지점으로 자르기 : str.substring(indexStart, indexEnd) : indexStart부터 indexEnd전가지 리턴

var str = 'Hello World!';

console.log(str.substring(2, 5)); //llo
console.log(str.substring(2)); //llo World!

 

시작 지점과 길이로 자르기 : str.substr(start, length) : start부터 length길이(갯수)의 문자열 리턴

var str = 'Hello World!';

console.log(str.substr(2, 5); //llo W

 

앞뒤 공백 없애기 : str.trim() : str 앞뒤 공백(띄어쓰기, 들여쓰기, 줄바꿈) 제거

 

<!DOCTYPE html>
<html>
  <head>
    <title>Couple Story</title>
    <meta charset="utf-8" />
    <link href="css/styles.css" rel="stylesheet" />
    <style>
        * {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-width: 992px;
  font-family: "Helvetica";
}

/* navigation bar */

.navbar {
  height: 66px;
  background-color: white;
  text-align: center;
  line-height: 66px;
}

#logo {
  vertical-align: middle;
}

/* main */

.main {
  background-image: linear-gradient(135deg, #B0A8FF 0%, #786FFF 100%);
  padding: 80px 0;
  min-height: calc(100vh - 66px);
}

.container {
  background: #FFFFFF;
  box-shadow: 2px 2px 4px 2px rgba(0,0,0,0.10);
  border-radius: 10px;
  width: 600px;
  margin: 0 auto;
  text-align: center;
  padding: 32px 66px;
}

.container h2 {
  font-size: 24px;
  color: #4A4A4A;
  margin: 0;
  margin-bottom: 28px;
}

.container h2 span {
  font-weight: 700;
  color: #786FFF;
}

.container .img-row {
  margin-bottom: 40px;
}

.container .img-row img {
  vertical-align: middle;
  margin: 0 6px;
}

.date-row {
  margin-bottom: 40px;
}

label[for=start] {
  font-size: 16px;
  color: #4A4A4A;
  line-height: 34.5px;
  vertical-align: middle;
  margin-right: 13px;
}

input[type=date] {
  border: 1px solid #786FFF;
  border-radius: 5px;
  padding: 8px 14px;
  vertical-align: middle;
  font-size: 16px;
}

#calculate {
  width: 100%;
  background: #786FFF;
  box-shadow: 0 2px 4px 0 rgba(0,0,0,0.50);
  border-radius: 5px;
  color: white;
  font-size: 18px;
  padding: 14px 0;
  border: none;
  cursor: pointer;
}
    </style>
  </head>

  <body>
    <div class="navbar">
      <img id="logo" src="images/logo.png" width="157">
    </div>

    <div class="main">
      <div class="container">
        <!-- 만난지 며칠? -->
        <h2>만난지 <span id="day-count">00</span>일째</h2>
        <!--결과값 대입 span쪽 대입 -->

        <!-- 만나기 시작한 날짜 -->
        <div class="date-row">
          <label for="start">시작일</label>
          <input type="date" name="start" id="start">
        </div>
        <!-- 1st string검색해서 (현재날짜 - 만난날 = 만난일)-->

        <!-- 2st 며칠됐는지 계산하기! -->
        <button id="calculate">결과 보기</button>
        <!-- alert로 결과보기-->
      </div>
    </div>

    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>

    <script>     
     $('#calculate').on('click',Button);
     function Button(){
      var date = new Date();
      var datein = new Date($('#start').val());  //??

      var date_Dialy = date.toLocaleDateString(); //date객체의 날짜 부분을 지역의 언어에 맞는 문자열 표현으로 반환
      var datein_Dialy = datein.toLocaleDateString(); //type:string
    
      var heartday = date - datein;
      var resultday = Math.floor(heartday / 1000 / 60 / 60 /24 + 1 );
      
      var strdatein = String(datein_Dialy);

      console.log(strdatein.indexOf()); //undefined, -1

      if(strdatein.indexOf() == -1){ 
        alert("시작 날짜를 정확히 입력해주세요.");

      }else{
        $('#day-count').text(resultday);
        alert(resultday + "일 입니다." ); 
              }
          }

    </script>
  </body>
</html>

 

4강. Array 정리노트

배열의 길이 : length

var brands = ['a', 'b', 'c'];
console.log(brands.length); //3

 

배열에서 특정값 찾기 : array.indexOf(item) : item이 포함되어 있는지 확인

1) 포함된 경우, item이 있는 인덱스 리턴

2) 포함되지않은 경우, -1 리턴

3) 여러번 포함된 경우, 처음 발견된 인덱스 리턴

var brands = ['a', 'b', 'c'];

console.log(brands.indexOf('c')); //2
console.log(brands.indexOf('d')); //-1

 

배열에 값 추가 : array.push(item1) : item1이 array배열의 끝에 추가

array.push(item1, item2, item3) : array 배열의 끝에 item1, item2, item3 순서대로 추가

var brands = ['a', 'b', 'c'];

brands.push('d');
console.log(brands); //['a', 'b', 'c', 'd'];

brands.push('e', 'f', 'g');
console.log(brands); //['a', 'b', 'c', 'd', 'e', 'f', 'g'];

 

배열에서 값 빼기 : array.pop() : array배열의 마지막 요소가 빠지고 마지막 요소가 리턴

var brands = ['a', 'b', 'c'];
var lastBrand = brands.pop();

console.log(lastBrand); //c  ........배열이 아니게 되는건가?
console.log(brands); //['a', 'b'] 

 

배열을 문자열로 바꾸기

var brands = ['a', 'b', 'c'];
console.log(brands.join()); //a, b, c  일반 문자열로 변환
console.log(brands.join('###')); //a###b###c 쉼표대체

 

5강. Date정리노트

객체 만들기

현재 날짜로 설정 : new Date() : 파라미터 없이 설정

var date = new Date();

 

원하는 날짜로 설정 : new Date(특정 날짜, 시간) : 파라미터에 원하는 날짜 설정

//1988년 6월 11일 5시 25분 30초
var date1 = new Date('June 11, 1988 05:25:30');
var date2 = new Date('1988-06-11ㅆ05:25:30');

//1988년 6월 11일 날짜만
var date3 = new Date('1988-06-11');
var date4 = new Date('06/11/1988');
var date5 = new Date('June 11 1988');

 

날짜 정보 받아오기

var date = new Date('June 11, 1988 05:25:30');

console.log(date.getFullYear()); //1988
console.log(date.getMonth()); //6 (0:1월,1:2월, ..)
console.log(date.getDate()); // 11
console.log(date.getDay()); // 6(0:일요일, 1:월요일..)
console.log(date.getHours()); // 5 
console.log(date.getMinutes()); // 25
console.log(date.getSeconds()); // 30
console.log(date.getMilliseconds()); // 0
console.log(date.toString()); // Sat Jun 11 1988 05:25:30 GMT+1000(KDT)
console.log(date.toLocaleString()); // 6/11/1988, 5:25:30 AM  배열의 요소를 나타내는 문자열 반환
console.log(date.toLocaleDateString()); // 6/11/1988  
console.log(date.toLocaleTimeString()); // 5:25:30 AM

getTime() : 1970년 1월 1일 00시(협정세계시, UTC)부터 몇 ms가 지났는지

var date = new Date('June 11, 1988 05:25:30');
console.log(date.getTime()); //581973930000 (ms)

console.log(date.getTime() + 'ms'); //581973930000ms
console.log(date.getTime()/1000 + '초'); //581973930초
console.log(date.getTime()/1000/60 + '분'); //9699565.5분
console.log(date.getTime()/1000/60/60 + '시간'); //161659.425시간

 

6강. 문자 개수 세기

7강. 데이터 분석하기

8강. 이메일 광고

9강. D-Day 계산기

 

 숨고르기 

1강. 개발자 엿보기

silicon valley, 개발자를 부탁해

 

2강. 영어는 필수인가요?

 

3강. 프로그래밍 마인드

 

4강. 참고사이트

JSFiddle

W3Schools

MDN JavaScript

 

 프로젝트: 드림 시퀀서 

1강. audio 다루기

var audioFile = new Audio("file location or url"); //생성
audioFile.play(); //재생
audioFile.pause(); //정지
audioFile.currentTime = 0; //오디오 파일 재생 위치 설정

 

2강. 드럼 시퀀서I

3강. 드럼 시퀀서II

//audioFile 배열에 파일 넣기
var audioFiles = [];
audioFile.push(new Audio("1번 오디오파일");
audioFile.push(new Audio("2번 오디오파일");
audioFile.push(new Audio("3번 오디오파일");
audioFile.push(new Audio("4번 오디오파일");
audioFile.push(new Audio("5번 오디오파일");
audioFile.push(new Audio("6번 오디오파일");
audioFile.push(new Audio("7번 오디오파일");
audioFile.push(new Audio("8번 오디오파일");
audioFile.push(new Audio("9번 오디오파일");


var loop = new Audio("오디오 경로");

//play, stop버튼
$("#play-btn").on('click', function(){
  loop.play();
}
$("#stop-btn").on('click', function(){
  loop.pause();
}

//키보드
$(document).on('keydown', function(event){
  if(Number(event.key) >=1 && Number(event.key) <=9 ){
  $('#cell' + event.key).addClass('playing'));
    var cur = audioFiles[Number(event.key) -1];
    cur.currentTime = 0;
    cur.play();
  }
});
$(document).on('keyup', function(){
  $('#cell').removeClass('playing'));
});








//마우스
var audioFile = [new Audio("audio/loop.mp3"), new Audio("audio/01_kick_drum.wav"), new Audio("audio/02_closed_hihat.wav"), new Audio("audio/03_open_hihat.wav"), new Audio("audio/04_clap.wav"), new Audio("audio/05_snap.wav"), new Audio("audio/06_crash.wav"), new Audio("audio/07_tom1.wav"), new Audio("audio/08_tom2.wav"), new Audio("audio/09_tambourine.wav")];
      $('#play-btn').on('click', function() {
        audioFile[0].play();
      });
      $('#stop-btn').on('click', function() {
        audioFile[0].pause();
        audioFile[0].currentTime = 0;
      });
      $(document).on('keydown', function(event) {
        if (Number(event['key'])){
          $('#cell' + event['key']).addClass('playing');
          audioFile[event['key']].play();
        }
      });
      $(document).on('keyup', function(event) {    
        if (Number(event['key'])){ 
          $('#cell' + event['key']).removeClass('playing'); 
          audioFile[event['key']].pause();
          audioFile[event['key']].currentTime = 0;
        } 
      });
      for (var i = 1; i < 10; i++){
        $('#cell' + i).on('mousedown', function() {
          $(this).addClass('playing');
          audioFile[this['id'][4]].play();
        });
        $('#cell' + i).on('mouseup', function() {
          $(this).removeClass('playing');
          audioFile[this['id'][4]].pause();
          audioFile[this['id'][4]].currentTime = 0;
        });
      }

 

4강. 드럼 시퀀서III

 

 세련된 코드란? 

1강. 스타일 가이드 흝어보기

띄어쓰기와 줄바꿈, 변수이름 규칙, 쓰지말아야 할 코드

에어비앤비, 깃허브, 구글 등의 스타일 가이드참고

https://github.com/tipjs/javascript-style-guide https://github.com/rwaldron/idiomatic.js/tree/master/translations/ko_KR https://google.github.io/styleguide/jsguide.html

 

2강. 작명 센스

좋은 이름 - 보기좋은 변수명, 이해하기 쉬운 변수명, 혼동되지않는 변수명

 

3강. Boolean의 활용

undefined : 아무것도 할당되지 않은 값

null : 비어있는 값

NaN (Not a Number) : 숫자가 아닌것을 숫자로 표현하려 할 때 반환 ex.parseInt

 

false와 true로 간주되는 것들

숫자 : 양수(true), 음수(false), 0(false)

문자열 : 빈 문자열(false), 문자열(true)

null(false), undefined(false), NaN(false)

if(str !== ''){
  console.log('str은 빈 문자열이 아닙니다.');
} else {
  console.log('str은 빈 문자열입니다.');
}

//▽

if(str){
  console.log('str은 빈 문자열이 아닙니다.');
} else {
  console.log('str은 빈 문자열입니다.');
}

 

다른 자료형을 불린으로 변형하는 법

var str = ''; //false
console.log(!str); //true
console.log(!!str); //false

 

4강. js파일 분리

<script src="script.js"></script>

 

반응형