[TIL] 23.03.14 JavaScript

dalCoding·2023년 3월 14일
0

Techit 블록체인 스쿨 3기 Today I Learned D+2

일단 만드는 JavaScript VOD강의 수강
코딩 유튜버 조코딩님의 강의

JavaScript를 사용하는 방법

  1. html
<body>
	<script>
      document.write("hello")
	</script>
</body>	
  1. js파일
<script src='myScript.js'></script>
//myScript.js
document.write('hello')

데이터 상자 만들기

variable - var 변수명;

(ES6) - 최신 자바 스크립트 문법
let 변수명 = 값;
const 변수명 = 값;

데이터의 특징 - 자료형
문자열(String)
숫자(정수int, 실수float)
불(bool): true, false

typeof 데이터

로또번호 추첨기

Math.random(); => 0이상 1미만 실수
parseInt() => 소수점은 버리고 정수로 변환

var lotto = [1,2,3,4,5,6];
index
lotto.push(); => 배열 추가

반복문
for(시작; 끝; 증가) {
반복하려는 코드
}

var lotto = [];
for(var i = 0; i < 6; i++) {
	lotto.push(parseInt(Math.random() * 45 + 1));
}
document.write(lotto);

while(조건) {
반복하려는 코드
}

.length => 배열의 길이

var lotto = [];
while(lotto.length < 6){
	var num = parseInt(Math.random() * 45 +1);
    if(lotto.indexOf(num) == -1) {
    	lotto.push(num);
    }
}
document.write(lotto);

조건문
if(조건) {
참일 경우
}

.indexOf(값) => 값이 있으면 위치, 없으면 -1

var lotto = [];
for(var i = 0; i < 6; i++) {
	var num = parseInt(Math.random() * 45 + 1)
	if (lotto.indexOf(num) == -1) {
    	lotto.push(num);
    } //lotto배열안에 num이 없으면(indexOf(num) == -1이면) lotto.push(num);
}
document.write(lotto);

.sort() =>배열 값 정렬
.sort((a, b)=> a-b) 숫자 오름차순 정렬

var lotto = [];
for(var i = 0; i < 6; i++) {
	var num = parseInt(Math.random() * 45 + 1)
	if (lotto.indexOf(num) == -1) {
    	lotto.push(num);
    }
}
lotto.sort((a,b)=>a-b);
document.write(lotto);

글자수 계산기

DOM (Document Object Model)
문서 객체 모델, 즉 DOM은 웹 페이지(HTML이나 XML 문서)의 콘텐츠 및 구조, 그리고 스타일 요소를 구조화 시켜 표현하여 프로그래밍 언어가 해당 문서에 접근하여 읽고 조작할 수 있도록 API를 제공하는 일종의 인터페이스
자바스크립트 같은 스크립팅 언어가 쉽게 웹 페이지에 접근하여 조작할 수 있게끔 연결시켜주는 역할을 담당

onkeydown="" 키보드가 눌릴 때 마다

substring(0,200); 200글자 미만

<textarea rows="3" id="jasoseol" onkeydown="counter();">자소서</textarea>
<script>
	function counter() {
    	var content = document.getElementById('jasosel').value;
        if(content.length > 200) {
        	content = content.substring(0, 200);
            document.getElementById('jasosel').value = content;
        }
         document.getElementById('count').innerHTML = '(' + content.length +'/200)';
    }
    counter();
</script>

미니스타크래프트

jQuery 라이브러리
document.getElementById('content').value;
$('#content').val();
간결한 문법, 편리한 api, 크로스 브라우징
$(선택자)행위

code.jquery.com => html 복붙

<script
 src="https://code.jquery.com/jquery-3.5.1.js"
 integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
 crossorigin="anonymous"></script>
<button id="click" onclick="hello();">클릭</button>
<script>
$('#click').click(hello);
</script>

익명 함수
$('#click').click(fucntion(){
console.log('hello');
});

.fadeIn(duration, complate)
.fadeIn(선택사항)

.animate(properties, [duration], [easing], [complete])

.fadeOut()

.css() => 변경하고 싶은 css 입력

콜백(callback) => 실행 함수 종료 후 다음 코드 실행

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>스타크래프트</title>
    <style>
        .background {
            position: relative;
            background-image: url('background.png');
            background-size: 500px 330px;
            width: 500px;
            height: 330px;
        }
        #drone {
            position: absolute;
            width: 100px;
            height: 100px;
            top: 100px;
            left: 60px;
        }
        #bunker {
            position: absolute;
            width: 150px;
            height: 150px;
            top: 80px;
            right: 20px;
        }
        #spit {
            display: none;
            position: absolute;
            top: 140px;
            left: 150px;
            width: 50px;
            height: 30px;
            z-index: 2;
        }
    </style>
</head>
<body>
    <h1 id='hp'>HP: 3</h1>
    <div class='background'>
        <img id='drone' src="drone.png" alt="drone">
        <img id='spit' src="spit.png" alt="spit">
        <img id='bunker' src="bunker.png" alt="bunker">
    </div>
    <script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>
    <script>
        var hp = 3;
        $('#drone').click(function() {
            $('#spit').fadeIn();
            $('#spit').animate({'left': '+=250px'});
            $('#spit').fadeOut(function(){
                hp = hp - 1;
                $('#hp').text('HP: ' + hp);
                if (hp == 0) {
                    $('#bunker').fadeOut();
                }
            });
            $('#spit').css({left: 150});
        });
    </script>
</body>
</html>

기념일 계산기

Date 객체
var now = new Date();
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date

<script>
        //1. Date 객체 생성
        var now = new Date();
        //2. 연도를 가져오는 메서드 .getFullYear()
        console.log(now.getFullYear());
        //3. 월 정보를 가져오는 메서드 .getMonth() {0: 1월, 1: 2월, ... 10: 11월, 11: 12월}
        console.log(now.getMonth());
        //4. 일 정보를 가져오는 메서드 .getDate()
        console.log(now.getDate());
        //5. 1970년 1월 1일 00:00:00을 기준으로 흐른 시간을 밀리초로 표시하는 메서드 .getTime()
        console.log(now.getTime());
        //6. 특정 일의 Date 객체 생성
        var christmas = new Date('2020-12-25');
        console.log(christmas);
        //7. 특정 ms의 Date 객체 생성
        var ms = new Date(1000);
        console.log(ms);
    </script>

만난 밀리초 = 오늘.getTime() - 사귄날.getTime()
만난 일 = 만난 밀리초를 일로 환산

<body>
	<h3 id='love'>0일째</h3>
</body>
<script>
	var now = new Date();
    var start = new Date('2020-06-30');

    var timeDiff = now.getTime() - start.getTime();
    var day = Math.floor(timeDiff / (1000 * 60 * 60 * 24) + 1);
    $('#love').text(day + '일째');
</script>

남은 밀리초 = 기념일.getTime() - 오늘.getTime()
만난 일 = 만난 밀리초를 일로 환산

<body>
	<p id='valentine'>0일 남음</p>
</body>
<script>
	var valentine = new Date('2023-02-14');
   var timeDiff2 = valentine.getTime() - now.getTime();
   var day2 = Math.floor.(timeDiff2 / (1000 * 60 * 60 * 24) +1);
   $('#valentine').text(day2 + '일 남음');
</script>

1000일의 밀리초 = 사귄날.getTime() + 999일의.getTime()
1000일 = new Data(1000일의 밀리초)

<body>
	 <p id='thousand-date'>0일 남음</p>
</body>
<script>
	var ms = start.getTime() + 999 * (1000 * 60 * 60 * 24);
	var thousand = new Date(ms);
	var thousandDate = thousand.getFullYear() + '.' + (thousand.getMonth()+1) + '.' + thousand.getDate();

	$('#thousand-date').text(thousandDate);
</script>    
<body>
	<p id='thousand'>0일 남음</p>		
</body>
<script>
 var timeDiff3 = thousand.getTime() - now.getTime();
        var day3 = Math.floor(timeDiff3 / (1000 * 60 * 60 * 24) + 1);
        $('#thousand').text(day3 + '일 남음');
</script>

0개의 댓글