[TIL] javascript

박동우·2023년 3월 17일

블록체인 스쿨 3기

목록 보기
4/72

[TIL] 2023-03-14

html파일 or js파일 별도로 작성도 가능
body 태그 안에 작성

  • html 파일에서 사용시 태그
<script></script>
  • js파일 사용시
  • 명령어
    document.write();
  • 데이터 상자 만들기
    변수 variable : var 변수명 = 값;
    최신버전(ES6)에서는 let, const를 var대신 사용하기도함
    string : '문자열'
    int: 정수형
    float : 실수형
    bool : true or false
    자료형 알아내는법 : typeof

로또 번호 추첨기

  • 함수
    Math.random(); -> 0~1미만의 실수 랜덤 출력
    parseInt(); -> 정수형으로 변환

  • 반복문
    for (시작; 끝; 증감;){
    반복코드
    }
    while (조건) {
    반복코드
    }
    .length -> 배열의 길이
    .sort(); -> 배열 정렬(디폴트 값은 앞자리 크기순서)
    .sort((a,b)=>a-b); -> 오름차순 정렬

  • 조건문
    if (조건) {참일경우실행}
    .indexOf -> 값이 있으면 위치인덱스, 없으면 -1

  • 배열(array)
    var 이름 = [1,2,3,4];
    이름.push(숫자); -> 마지막 배열에 추가

DRY 지양하기

자소서 글자수 세기

  • DOM(document object model)
    html 코드에 쉽게 접근하기 위한 모델(js에서 html 태그에 접근 가능)
var content = document.getElementById('jasoseol').value;
console.log(content); -> content.length(글자수)

document.getElementById().value

<span id="count">(0/200)</span>
    <script>
        var content = document.getElementById('jasoseol').value;
        document.getElementById('count').innerHTML = '('+content.length+'/200)';
    </script>

document.getElementById().innerHTML

  • 함수
    function 함수이름() {}
  • 이벤트
    사용하고자 하는 html태그 안쪽에다가 입력
    ex) onkeydown: 키보드를 누를때 마다 이벤트
	<textarea 이벤트=이벤트핸들링></textarea>
  • 글자수 자르기
    substring(a,b) -> a부터 b미만까지 자름
 if(content.length>200){
                content = content.substring(0,200);
                document.getElementById('jasoseol').value = content;
            }
  • 최종
function counter() {
            var content = document.getElementById('jasoseol').value;
            if(content.length>200){
                content = content.substring(0,200);
                document.getElementById('jasoseol').value = content;
            }
            document.getElementById('count').innerHTML = '('+content.length+'/200)';
        }
        counter();

미니 스타크래프트

  • jQuery
    js를 쉽게 사용할 수 있게 해주는 라이브러리
    기본구조 : $(선택자).행위;
	console.log($('#content').val());
        function hell() {
            console.log('hello');
        }
        //.click()
        $('#click').click(hell);
-> #click은 html 태그를 가르키고, .click(hell)은 위 함수를 가르킨다
  • 익명함수
    한번만 사용하는 함수를 간단히 사용하기 위하여 jQuery에서 한번에 사용하는 함수
    $('#click').click(function(){
                console.log('hello');
            });
  • jquery 함수들
  1. .fadeIn
    나타내기

  2. .animate

	$('#spit').animate({left: '+=250'});
  1. .fadeOut
    없애기
$('#spit').fadeOut(function() {
                hp -= 1;
                $('#hp').text('hp:'+hp);
            });
-> 콜백함수: 동작이 모두 끝난 후 다음 동작 실행
  1. .css
    css변경
  1. .text
    html 글자 변경
  • 최종
<script>
        var hp = 3;
       $('#drone').click(function(){
            $('#spit').fadeIn();
            $('#spit').animate({left: '+=250'});            
            $('#spit').fadeOut(function() {
                hp -=1;
                $('#hp').text('HP: '+hp);
                if(hp == 0){
                    $('#bunker').fadeOut();
                }
            });
            $('#spit').css({left: 150});
        });
</script>

기념일 계산기

  • 객체(object)
var person = {
            //키 name: 'jocoding', //값(value)
            //속성명 sayHello: function() { console.log('hello'); } //속성값
        }입력하세요
-> 배열,객체,함수(매세드)도 입력 가능
  • Date 객체
    객체 생성 : var 이름 = new Date();
    .getFullYear()
    .getMonth()
    .getDate()
    .getTime() -> ms단위
  • git 사용법
    // 시작하기: git init
    // 유저 이름 설정: git config --global user.name "codelion-jocoding"
    // 이메일 등록: git config --global user.email #####@gmail.com
    // 파일 추가: git add .
    // 메세지 입력: git commit -m "first commit"
    // 보낼 곳 등록: git remote add origin https://github.com/codelion-jocoding/myrepo.git
    // 보낼 곳으로 코드 전송: git push origin master
profile
HELLO!

0개의 댓글