💡Java Script 기초 문법
<body>
...
<script> // 열고 닫는 태그, 여기서부터 Java Script 코드
document.write('하고 싶은 말');
</script>
세미클론 : ; // 하나의 명령이 끝남
ex) document.write('안녕'); // Java Script는 유연한 언어라서 세미콜론을 붙이지 않아도 잘 작동함. but, 줄 바꿈 필수
- 주석 : // , /* */
- 변수 (var)
: 데이터를 이름표가 있는 상자에 담아줌
var 변수이름 = 값; -> var num = 10; // 변수이름 = 상자이름, 값 = 넣고싶은 데이터
- 데이터 자료형
문자열 (string) : '안녕', "안녕"
정수 (int) : -1, 0, 1
실수 (float) : 0.25
불 (bool) : true or false
#1 로또 번호 추첨기
//로또 추첨 번호 만들기 (중복 안됨, 1부터 45까지 숫자만)
<script>
var lotto = [];
while (lotto.length < 6) { // 로또 배열의 길이가 6이 될 때까지 반복
var num = parseInt(Math.random() * 45 + 1); // 1~45 범위의 정수를 num에 담기
if (lotto.indexOf(num) == -1) { // 뽑았던 숫자와 겹치는게 없을 때
lotto.push(num); // 로또라는 배열에 num을 넣는다!
}
}
lotto.sort((a,b)=>a-b); // 보기 좋게 오름차순 정렬하기!
document.write("<div class='ball ball1'>" + lotto[0] + "</div>");
document.write("<div class='ball ball2'>" + lotto[1] + "</div>");
document.write("<div class='ball ball3'>" + lotto[2] + "</div>");
document.write("<div class='ball ball4'>" + lotto[3] + "</div>");
document.write("<div class='ball ball5'>" + lotto[4] + "</div>");
document.write("<div class='ball ball6'>" + lotto[5] + "</div>");
</script>
Math.random() // 임의의 실수 형 숫자 생성
parseInt() // 소수점 버리고 정수로 변환
- 배열 (Array)
: 하나의 변수 안에 여러 개의 값을 저장
ex) var lotto = [1, 2, 3, 4, 5, 6];
lotto [2] = 3 // 배열에서 Index 순서는 앞에서부터 0번째, 1번째...
lotto.push(7); // 로또라는 배열의 마지막에 7이란 요소를 추가함
- 반복문
for 문 -> 특정 횟수만큼
ex) for(var i=0; i <6; i++){ } // 0부터 시작해서 6이 되기 전까지 1씩 증가하는 반복문
while 문 -> 특정 조건만큼
ex) while(lotto.length <6) // 로또 배열의 길이가 6이 되기 전까지 반복
- 조건문
if (조건) { 경우 }; // 조건을 만족했을 때 어떤 경우를 실행함
- DOM (Document Object Model)
document : DOM의 진입점 역할
ex) document.getElementById(' '). value; // 값 가져오기
- Console
console.log(' '); // 콘솔 창에 출력
- 함수 : 명령 모음
function 함수이름(){ 명령어 1; 명령어 2;} 사용할} 때 -> 함수이름();
#2 글자 수 계산기
function counter(){ //counter 함수를 정의
var content = document.getElementById('jasoseol').value;
if(content.length > 200){
content = content.substring(0,200); // 200글자가 넘으면 글자 수 자르기
document.getElementById('jasoseol').value = content;
}
document.getElementById('count').innerHTML = '('+ content.length + '/200)';
}
counter();
. substring(a, b) // a이상 b미만까지 정하고 b 이상이 되면 그 뒤로 자르기
#3 미니 스타크래프트 게임
var hp = 3;// 기본 HP는 3으로 설정
$('#drone').click(function(){ // 드론을 눌렀을 때 함수 실행
$('#spit').fadeIn(); // 침이 나타남
$('#spit').animate({'left': '+=250px'}); // 침이 오른쪽으로 250만큼 움직임
$('#spit').fadeOut(function(){ // 침이 사라지면서 함수 실행
hp = hp - 1; // HP는 침이 나가고 나서 1 씩 깎임
$('#hp').text('HP: '+ hp) // 현재 HP를 출력
if(hp==0){ // HP가 0이 됐을 때
$('#bunker').fadeOut(); // 벙커는 사라짐
}
});
$('#spit').css({left: 150}) // 침이 오른쪽으로 이동하고 나서 원래 자리로 돌아감
});
- jQuery
: JavaScript 사용 쉽게 해주는 라이브러리
장점
1. 간결한 문법
2. 편리한 API
3. 크로스 브라우징
$('#선택자'). 행위;
ex) $('#message'). click(hello); // message를 클릭하면 hello가 출력
* 익명함수
ex) ('#message'). click(function(){ 함수 내용 } ; // message를 클릭하면 익명함수를 만든 후 함수 내용을 실행함
- 객체(object)
: 여러 개의 값을 담는 자료형
ex) var person = { name: '다원'. age: 24 } // person은 객체이름, name과 age는 키(key=속성명), '다원'과 24는 값(value=속성값)
++ 배열, 객체, 함수도 들어갈 수 있음
person.name; // 다원
person.sayHello(); // sayHello 메서드의 함수 실행
*JavaScript의 모든 것은 객체다*
#4 기념일 계산기
<script>
var now = new Date();// Date 객체 생성
var start = new Date('2020-06-30');
/*2020-06-30로부터 지금이 몇 일째 됐는지 계산하기*/
var timeDiff = now.getTime() - start.getTime();
var day = Math.floor(timeDiff / (1000 * 60 * 60 * 24) + 1);//ms를 date로 변환하는 수식
$('#love').text(day + '일째');
/*기념일까지 남은 날짜 계산하기*/
var valentine = new Date('2021-02-14');
var timeDiff2 = valentine.getTime() - now.getTime();
var day2 = Math.floor(timeDiff2 / (1000 * 60 * 60 * 24) + 1);
$('#valentine').text(day2 + '일 남음');
/*1000일이 언제인지 계산하기*/
var thousand = new Date(start.getTime() + 999 * (1000 * 60 * 60 * 24));
var thousandDate = thousand.getFullYear() + '.' + (thousand.getMonth()+1) + '.' + thousand.getDate();
$('#thousand-date').text(thousandDate);
/*1000일까지 남은 날짜 계산하기*/
var timeDiff3 = thousand.getTime() - now.getTime();
var day3 = Math.floor(timeDiff3 / (1000 * 60 * 60 * 24) + 1);
$('#thousand').text(day3 + '일 남음');
</script>
- Date 객체 생성
var now = new Date;
- 연도를 가져오는 메서드. getFullYear()
console.log(now.getFullYear());
- 월 정보를 가져오는 메서드. getMonth() {0: 1월, 1: 2월,... 10: 11월, 11: 12월}
console.log(now.getMonth());
- 일 정보를 가져오는 메서드. getDate()
console.log(now.getDate());
- 1970년 1월 1일 00:00:00을 기준으로 흐른 시간을 밀리초로 표시하는 메서드. getTime()
console.log(now.getTime());
- 특정 일의 Date 객체 생성
var birthday = new Date('2000-10-21');
- 특정 ms의 Date 객체 생성
var ms = new Date(10000);
👾 Git 명령어
|
📖 HTML (이력서 만들기)
<!-- 기본 골격 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>다원의 이력서</title>
<link rel="stylesheet" href="codelion.css">
</head>
<body>
<h1>박다원</h1>
<p>HTML/백엔드 개발자</p>
<footer>copyright daone. All rights reserved.</footer>
</body>
</html>
🖍️ CSS 꾸미기
|