2023.03.08 학습일지

이준영·2023년 3월 8일
0
post-thumbnail

복습


함수 선언 / 호출 (직접호출, 이벤트를 통해서 호출)

  • 객체 : 새로운 자료형 선언
    내부구성 - 필드(멤버변수), 생성자, 메서드

  • 선언방법 (클래스명 무조건 대문자로 시작)
    1. class (최신)

class 클래스명 {
}

객체 변수 선언은 let 객체변수(인스턴스) = new 클래스명();

객체변수 사용해서 멤버변수 / 메서드 접근 (. = 메모리 참조 연산자 통해)

2. 함수(생성자) 사용 (지나가는 정도)

const 클래스명 = function() {
}

객체 변수 선언은 똑같이 let 객체변수(인스턴스) = new 클래스명();

3. JSON(Javascript Object Notation) (많이씀)

const 객체변수명 = {
속성명(키):값,
속성명(키):값,
or 메서드명:function(){
}
...
}

<-- 여기까지 복습




  • 내장 객체
    기본객체 - 확장 자료형
    멤버변수
    메서드

DOM / BOM
https://developer.mozilla.org/ko/docs/Web 참조

외부 객체 - 외부에서 가져오는 객체(유료도 있음)
https://www.highcharts.com/demo 참조

Object

최상위 객체(javascript 거의 모든 객체는 Object의 인스턴스)

    <script type="text/javascript">
        let obj = new Object();

        //object 객체 세부 정의 내용
        console.log(obj);
        //toString() - 내부(멤버변수) 내용 문자열로 출력
        //딱히 선언 안해도 내부적으로 object에 있는 함수라 사용 가능하다(상속)
        console.log(obj.toString());
    </script>



toString

내부 내용 문자열로 출력해준다.

        let student = {
            name: "홍길동",
            grade: '1학년',

            //재선언
            toString: function() {
                return this.name + ':' + this.grade;
            }
        console.log(student);
        console.log(student.toString()); 
        };



문자열

    <script type="text/javascript">
        //문자열 객체변수
        let str1 = 'Hello String';  //(편법)
        let str2 = "Hello String";  //(정식)
        let str3 = new String('Hello String');
        
        //일반적인 문자열 형태로 출력
        console.log(str2);
        //객체구조로 출력
        console.log(str3);
        console.log(str3.toString());  --> 문자열로 출력해줌
    </script>



String 클래스 메서드 (중요! 숙지)


length : 문자열 길이 출력

ex 문자열 -> let str1 = 'Hello String, 안녕 String';

//문자열의 길이 출력
console.log(str1.length);
        


문자 분리(배열이나 charAt())

//문자 하나씩 분리 -> 배열 or charAt() 사용
console.log(str1[0]);
console.log(str1.charAt(0));
        
//맨 마지막자 분리
console.log(str1.charAt(str1.length-1));


문자열 분리(substr / substring / slice)

      //문자열 분리 -> substr / substring / slice
        console.log(str1.substr(6));   // 6부터 끝까지
        console.log(str1.substr(0,5)); // 0부터 5만큼(자신포함)까지
        //substring / slice 차이
        console.log(str1.substring(6, 12)); // 6~index-1(여기선 11)까지 문자 잘라내기
        console.log(str1.slice(6, 12)); // substring과 동일


문자열 검색(indexof, lastIndexOf, search, includes)

//문자열 검색 - 위치(같은 문자면 제일 앞에 있는 것 찾아줌), 없으면 -1
console.log(str1.indexOf('l'));
console.log(str1.indexOf('s'));
console.log(str1.indexOf('S',7)); //7번째 위치부터 S 찾기
console.log(str1.lastIndexOf('S')); //뒤에서부터 찾기

console.log(str1.search('S')); //문자열 검색

console.log(str1.includes('0'));//str1가 0을 포함하고 있으면 true 출력 없으면 false


대소문자 변환(toUpperCase, toLowerCase)

//대소문자 변환
console.log(str1.toUpperCase()); //전부 대문자 변환
console.log(str1.toLowerCase()); //전부 소문자 변환

//변수 할당하여 사용
let str2 = 'abc'.toUpperCase();
console.log(str2);


문자열 치환(replace)

//문자열 치환
console.log(str1.replace('Hello','안녕')); --> Hello가 안녕으로 치환(변환)


문자열 결합(+, concat)

console.log(str1 + ' hello 안녕 ');
//concat - 가변인자로 여러개 결합 가능
console.log(str1.concat(' hello 안녕 ','1',' 2'));


구분자 중심의 문자열 분리(split) => (배열 출력)

let str1 = '사과,딸기,수박,참외';

//구분자 중심의 문자열 분리 => 결과 배열출력
let arr1 = str1.split(',');
console.log(arr1);

//for문으로 전체 배열값 각각 뽑기
for(let value of arr1){
console.log(value);
}


응용 - 어떤 변수든 단어 첫글자마다 대문자로 출력하기

<body>
    <script type="text/javascript">
        let data = 'hong gil dong';

        let words = data.split(' ');  //공백을 구분점으로 분리

        let result = '';
        for(let word of words){  //반복해서 전체 출력
            //분리된 글자 중 첫글자만 대문자로 바꾸기
            console.log(word.substring(0 , 1).toUpperCase()
            + word.substring(1));
            //result('')로 문자열을 결합(공백 플러스하여 각 단어마다 띄어쓰기 기능 추가)
            result += word.substring(0 , 1).toUpperCase()
            + word.substring(1) + ' '; // ' '는 단어 사이 공백 추가하기 위함
        }
        
        console.log(result);
    </script>
</body>

응용문제 함수화 시키기

<head>
</style>
<script type="text/javascript">
        //첫글자만 대문자로 만들어주는 함수        
        const capit = function(data) {
        
            let words = data.split(' ');  //공백을 구분점으로 분리
            let result = '';
            for(let word of words){  //반복해서 전체 출력
            //result('')로 문자열을 결합(공백 플러스하여 각 단어마다 띄어쓰기 기능 추가)
                result += word.substring(0 , 1).toUpperCase()
                + word.substring(1) + ' '; // ' '는 단어 사이 공백 추가하기 위함
            }
            return result
        };
</script>
</head>
<body>
    <script type="text/javascript">
        let result = console.log(capit('hong gil dong'));


    </script>
</body>
결과는 동일





Number 클래스 메서드


저장할 수 있는 최댓 최솟값(MAX_VALUE or MIN_VALUE)

        //저장할 수 있는 최댓 최솟값
        console.log(Number.MAX_VALUE);
        console.log(Number.MIN_VALUE);



소수점 처리(toFixed(n))

        //소수점 처리(toFixed) - n번째 자리에서 끊어줌
        let num = 273.1234567;
        console.log(num.toFixed(1));
        console.log(num.toFixed(3));





Date 함수 - 표준시 출력(today / today.toLocaleString)

        let today = new Date();

        //표준시로 출력
        console.log(today);
        console.log(today.toString());
        
        //지역별로 출력(우리 기준 한국)
        console.log(today.toLocaleString());



Date 함수 - 다양한 시간들 출력 (today.get~~~())

    <script type="text/javascript">
        let today = new Date();
        //년 월 일
        let strToday = today.toLocaleString();
        console.log(strToday.substring(0,11));  // 년 월 일만 잘라서 출력됨

        console.log(today.getFullYear());  //년도
        console.log(today.getMonth() + 1); //월, month는 0부터 출력이라 +1 해줘야함
        console.log(today.getDate()); //일
        console.log(today.getDay());  //요일(일요일 0 기준)
        
        //시 분 초
        console.log(today.getHours());
        console.log(today.getMinutes());
        console.log(today.getSeconds());

        //1970 년 1 월 1 일 00:00:00 부터 지금까지를 밀리초로 출력
        console.log(today.getTime());
    </script>



특정 시간대에 대한 정보

		//특정 시간에 대한 정보
        let date1 = new Date( 2023, 3-1, 8, 10, 10, 40);  //직접 지정해주기, 3-1을 한 이유는 0이 1부터 나와서
        console.log(date1.toLocaleString());



특정 월의 마지막 일 구하기

        //월의 마지막 .. 2월

        let date2 = new Date(2023, 3-1, 1-1);  // 1-1을 하면 그 전 달의 마지막 일
        console.log(date2.toLocaleString());



특정 시간 연산(gettime, getdate 사용)

    <script type="text/javascript">
        let date1 = new Date(2023, 3-1, 3);
        let date2 = new Date(2023, 3-1, 1);

        //gettime 기준으로 - 한 것(밀리초로 출력됨)
        let interval1 = date1 - date2;
        console.log(interval1);
        let interval2 = date1.getTime() - date2.getTime();
        console.log(interval2);

        // 둘의 차가 며칠차이인지 구하기.
        let date3 = interval2 / (60*60*24*1000);  //하루를 밀리초로 변환
        console.log(date3);
        console.log(date1.getDate() - date2.getDate());

        //며칠 전, 며칠 후
        let date = new Date();
        date.setDate(date.getDate() + 7);  //현재 날짜에서 7일 더함
        console.log(date.toLocaleString());
    </script>






Math 메서드


올림(ceil), 내림(floor), 반올림(round)

    <script type="text/javascript">
        //올림(ceil), 내림(floor), 반올림(round)
        console.log(Math.ceil(5.6));
        console.log(Math.ceil(5.5));
        console.log(Math.ceil(5.4));

        console.log(Math.floor(5.6));
        console.log(Math.floor(5.5));
        console.log(Math.floor(5.4));

        console.log(Math.round(5.6));
        console.log(Math.round(5.5));
        console.log(Math.round(5.4));

    </script>



최대, 최소 (Math.max, Math.min)

    <script type="text/javascript">
        //최대,최소(괄호 안의 개수는 가변인자)
        console.log(Math.max(52, 273, 97, 31));
        console.log(Math.min(52, 273, 97, 31));

    </script>



난수, 임의의 추출 - Math.random() (많이 쓰임)

    <script type="text/javascript">
        //난수, 임의의 추출
        // 0 <= x < 1 임의의 실수 출력
        console.log(Math.random());
        console.log(Math.random());
        console.log(Math.random());
    </script>



응용 (0~9까지 정수 랜덤하여 뽑기)

	<script type="text/javascript">
        // 0~9까지의 임의의 정수를 뽑기
        // 0 * 10 <= x < 1 * 10 해주고 실수를 정수화
        console.log(parseInt(Math.random()*10));
    </script>



배열(Array) 메서드

배열 - 빈 공간 배열 선언 - new Array(n)

        //4개의 빈 공간 배열 생성(값이 아닌 크기값)
        let arr4 = new Array(4);
        console.log(arr4);



배열 결합(concat), join()

join() - 특정 문자를 붙인다. ((' ')를 넣으면 공백으로 나옴) --> 구분자로 분리하는 split과 반대

    <script type="text/javascript">
        let arr1 = new Array(1, 2, 3, 4);
        let arr2 = new Array(5, 6, 7, 8);

        //결합
        let arr3 = arr1.concat(arr2);
        console.log(arr3);
        
		console.log(arr1.join(' '));
        
    </script>



배열 추출(pop) / 추가(push)

        let arr1 = new Array(1, 2, 3, 4);
        
       //추출
        let value = arr1.pop();   --> 마지막에 넣은 데이터를 빼온다.
        console.log(value);   --> 4를 빼옴
        console.log(arr1);    --> 1,2,3만 남음
        
		arr1.push(5);    --> 해당 숫자를 마지막에 추가한다.
        console.log(arr1);



배열 뒤집기(reverse)

        let arr1 = new Array(1, 2, 3, 4);
        
        //배열 뒤집기
        arr1.reverse();
        console.log(arr1);



배열 잘라내기(slice)

		let arr1 = new Array(1, 2, 3, 4);
        
        //배열 잘라내기
        let subarr = arr1.slice(1,3);  인덱스 1~2까지의 값이 출력
        console.log(subarr);



배열 위치 찾기(indexOf / lastIndexOf)

		let arr1 = new Array(1, 2, 3, 4);
        
        
        console.log(arr1.indexOf(1));  // 앞에서부터 찾기
        console.log(arr1.lastIndexOf(1));  //뒤에서부터 찾기(값은 동일)
        





forEach

    <script type="text/javascript">
        let arr1 = new Array(10, 20, 30, 40);

        //for
        for(let i = 0; i<arr1.length; i++) {    --> 전체 배열 값 출력
            console.log(arr1[i]);
        }

        //메서드
        //forEach - > 데이터 값의 개수만큼 for문 돌아간다.
        arr1.forEach(function(element, i) {    // 값, 인덱스 순
            console.log('함수 호출 : ', element, i);

        });

        //arr1의 합계
        let sum = 0;
        arr1.forEach(function(data) {
            sum += data;
        });
        console.log(sum);
    </script>





응용 문제 - 주민등록번호 체크 프로그램 만들기

방법 1

<body>
    <script type="text/javascript">
        const jumin = 'xxxxxx-xxxxxxx';

        //replace로 - -> ''로 대체
        let strJumin = jumin.replace('-','');
        //console.log(strJumin);

        //substring으로 한자씩 분리
        let num01 = Number(strJumin.substring(0,1) * 2);
        let num02 = Number(strJumin.substring(1,2) * 3);
        let num03 = Number(strJumin.substring(2,3) * 4);
        let num04 = Number(strJumin.substring(3,4) * 5);
        let num05 = Number(strJumin.substring(4,5) * 6);
        let num06 = Number(strJumin.substring(5,6) * 7);
        let num07 = Number(strJumin.substring(6,7) * 8);
        let num08 = Number(strJumin.substring(7,8) * 9);
        let num09 = Number(strJumin.substring(8,9) * 2);
        let num10 = Number(strJumin.substring(9,10) * 3);
        let num11 = Number(strJumin.substring(10,11) * 4);
        let num12 = Number(strJumin.substring(11,12) * 5);
        let num13 = Number(strJumin.substring(12,13));

        let sum = num01 + num02 + num03 + num04 + num05 + num06 + num07 +
         num08 + num09 + num10 + num11 + num12;

        let result = (11 - (sum % 11)) % 10;

        if(num13 == result) {
            console.log('번호형식 맞음');
        }
        else {
            console.log('번호형식 틀림');
        }     
    </script>
</body>

방법 2 (split을 이용하기)

<body>
    <script type="text/javascript">
        const jumin = 'xxxxxx-xxxxxxx';
        const checkjumin = '234567-8923451';

        let sum1 = 0, sum2 = 0;
        let jm = jumin.split('-');
        //console.log(parseInt(spjumin.join('')));
        let ckjm = checkjumin.split('-');
        //console.log(parseInt(ckjm.join('')));

        for(let i = 0; i < 6; i++) {
        sum1 += (jm[0].charAt(i) * ckjm[0].charAt(i));

        sum2 += (jm[1].charAt(i) * ckjm[1].charAt(i));      
        }

        let result = ((11 -((sum1 + sum2) % 11)) % 10);

        if(result == jm[1].charAt(6)) {
            console.log('주민등록번호가 맞습니다. ' + result);
        }
        else {
            console.log('주민등록번호가 아닙니다. ' + result);
        }
    </script>
</body>

방법3 (replace 사용하기)

<body>
    <script type="text/javascript">
        const jumin = 'xxxxxx-xxxxxxx';
        const checkjumin = '234567-8923451';

        let sum1 = 0, sum2 = 0;
        let jm = jumin.replace('-','');
        console.log(jm[2]);
        //console.log(parseInt(spjumin.join('')));
        let ckjm = checkjumin.replace('-','');
        //console.log(parseInt(ckjm.join('')));

        for(let i = 0; i < 12; i++) {
        sum1 += (jm[i] * ckjm[i]);      
        }

        let result = ((11 -((sum1 + sum2) % 11)) % 10);

        if(result == jm[12]) {
            console.log('주민등록번호가 맞습니다. ' + result);
        }
        else {
            console.log('주민등록번호가 아닙니다. ' + result);
        }
    </script>
</body>

profile
끄적끄적

0개의 댓글