JavaScript_VSC

03. 기본문법 (변수)

76beny 2022. 6. 22. 23:49

변수

- JS에서 데이터를 담을 수 있는 공간, Client 메모리에 생성되고 활용됨
- Type은 처음부터 갖지 않는 특성을 가지고, 값이 실제로 Asign(=)될떄 변수의 Type이 결정됨
- 전역변수 사용 시, 특정한 키워드 없이 선언하면 된다. ex)value = 10;
- var : 일반적인 변수 script가 선언된 곳에서만 활용되고 버려짐 ex)var value = 10;
- let : 임시 변수로 이름을 중복해서 사용할 수 없는 변수 ex)let value = 10;
- const : 상수로 선언시 값을 변경 할 수 없음!
 
    <script>
        //num0;  선언만으로는 사용 불가! 반드시 한번이라도 값이 초기화 해야함
        num1 = 10;
        var num2 = 20; //일반적으로 var을 붙이는 것을 추천
        var num3 = num1 + num2;

        //document.write('num0 : ' + num0 + '<br>');  초기화 안된 변수 사용해서 불가능!
        document.write('num1 : ' + num1 + '<br>');
        document.write('num2 : ' + num2 + '<br>');
        document.write('num3 : ' + num3 + '<br>' + '<hr>');


        str1 = 'Hello';
        var str2 = 'javascript';
        var str3 = str1 + str2 + 'word!';

        document.write('str1 : ' + str1 + '<br>');
        document.write('str2 : ' + str2 + '<br>');
        document.write('str3 : ' + str3 + '<br>' + '<hr>');


        //문자열 + 숫자 = 문자 ,    숫자/문자가 혼합된 경우 반드시 원하는 결과가 나오게끔 괄호 필수!
        document.write('str3 + num3 : ' + str3 + num3 + '<br>');
        document.write('숫자 + num3 + str3 : ' + 1000 + num3 + str3 + '<br>');
        document.write('숫자 + num3 + str3 : ' + (1000 + num3) + str3 + '<br>' + '<hr>');

        let val1 = 10; //ES6 문법으로 약간 최신식?(2016)
        val2 = 20;
        const con1 = 30;

        document.write('val1 : ' + val1 + '<br>');
        document.write('val2 : ' + val2 + '<br>');
        document.write('con1 : ' + con1 + '<br>' + '<hr>');

        //val은 재정의 가능!
        val1 = '안녕하세요?';
        val2 = '하이하이?';
        // con1='안녕?'; => con은 다시 재정의 하는 경우 문법오류 발생함
        document.write('val1 : ' + val1 + '<br>');
        document.write('val2 : ' + val2 + '<br>');
        document.write('con1 : ' + con1 + '<br>' + '<hr>');

        //let이 활용되는 범위 Test, 결론 : 블록 안에서만 임식값이 허용됨! 
        let letValue = 10;
        var varValue = 20;

        document.write('letValue : ' + letValue + '<br>'); //10출력
        document.write('varValue : ' + varValue + '<br>'); //20출력
        {
            let letValue;
            var varValue;
            document.write('letValue : ' + letValue + '<br>'); //undefined
            document.write('varValue : ' + varValue + '<br>'); //20
        }
        document.write('letValue : ' + letValue + '<br>'); //10
        document.write('varValue : ' + varValue + '<br>'); //20
    </script>

 

script영역이 끊어져도 앞에서 선언한 변수는 뒤에서도 활용 할 수 있음

    <script>
        document.write('val1 : ' + val1 + '<br>');
        document.write('val2 : ' + val2 + '<br>');
        document.write('con1 : ' + con1 + '<br>');
        document.write('letValue : ' + letValue + '<br>'); //10
        document.write('varValue : ' + varValue + '<br>'); //20
    </script>

자료형 확인 : typeof

-변수의 type알기 위해 활용변수를 인자로 활용할때 type아닌 경우를 미리 예외처리 용도로 활용

    <script>
        document.write('문자열 1 : ' + typeof('Hello') + '<br>');
        document.write('문자열 2 : ' + typeof(str1) + '<br>');
        document.write('문자열 3 : ' + typeof(val1) + '<br>');

        document.write('숫자 1 : ' + typeof(123) + '<br>');
        document.write('숫자 2 : ' + typeof(num1) + '<br>');
        document.write('숫자 3 : ' + typeof(10.41414) + '<br>');
        document.write('숫자 4 : ' + typeof(-3122) + '<br>');


        //실사용예시
        if (typeof(val1) == 'string') {
            document.write('문자열입니다.<br>')
        } else {
            document.write('문자열이 아닙니다!<br>')
        }

        var isValue = true;
        document.write('논리값 1 : ' + typeof(true) + '<br>');
        document.write('논리값 2 : ' + typeof(false) + '<br>');
        document.write('논리값 3 : ' + typeof(isValue) + '<br>');

        var isNull; //null상태임
        document.write('값이없는 변수 : ' + typeof(isNull) + '<br>');
        document.write('숫자 아닌지 확인 : ' + isNaN(isNull) + '<br>');
        document.write('null확인법 : ' + (isNull == null) + '<br>');
    </script>

문자열

    <script>
        var str = 'Hello!!';
        document.write(str.toUpperCase() + '<br>'); // 대문자로
        document.write(str.toLowerCase() + '<br>'); // 소문자로
        document.write(str.length + '<br>'); // 길이
        document.write(str.indexOf('l') + '<br>'); // 문자열 찾기 (앞에서부터)
        document.write(str.indexOf('llo') + '<br>'); // 문자열 찾기 (앞에서부터)
        document.write(str.lastIndexOf('l') + '<br>'); // 뒤에서 문자열 찾기
        document.write(str.charAt(1) + '<br>'); // 위치에서 문자 가져오기
        document.write(str.substr(1, 4) + '<br>'); // 문자열 자르기 
        document.write(str.split('') + '<br>'); // 공백인 경우 문자열이 모두 분리  
        document.write(str.split('e') + '<br>'); // e 기준으로 2개의 문자열로 분리
        document.write('Hello javascript world!'.split(' ') + '<br>' + '<hr>'); // 공백으로 분리

        // 문자열 자르기 활용법
        str = 'Hello javascript world !';
        let array = str.split(' ');
        document.write(array + '<br>'); // 배열 내용
        document.write(array.length + '<br>'); // 길이
        document.write(array[0] + '<br>');
        document.write(array[1] + '<br>');
        document.write(array[2] + '<br>');
        document.write(array[3] + '<br>');
        document.write(array[4] + '<br>'); // 없지만 안죽는다!
    </script>

 

숫자

    <script>
        document.write('절대값 : ' + Math.abs(-10) + '<br>');
        document.write('랜덤값 : ' + Math.random() + '<br>');
        document.write('랜덤값(1~100) : ' + Math.floor((Math.random() * 100 + 1)) + '<br>');
        document.write('반올림1 : ' + Math.round(3.46) + '<br>');
        document.write('반올림2 : ' + Math.round(3.56) + '<br>');
        document.write('반올림3 : ' + Math.round(3.56 * 10) / 10 + '<br>'); // 소수점 조절 방법
        document.write('내림1 : ' + Math.floor(3.44) + '<br>');
        document.write('내림2 : ' + Math.floor(3.56) + '<br>');
        document.write('올림1 : ' + Math.ceil(3.44) + '<br>');
        document.write('올림2 : ' + Math.ceil(3.56) + '<br>');
    </script>

 

숫자 - 문자열 변환

    <script>
        var num1 = 10;
        document.write(num1 + '<br>');
        document.write(typeof(num1) + '<br>');
        document.write('' + num1 + '<br>');
        document.write(typeof('' + num1) + '<br>'); // 방법1. 문자열 + 숫자, 추천!!
        document.write(typeof(String(num1)) + '<br>'); // 방법2. string() 활용

        document.write('' + num1 + 20 + '<br>'); // 1020
        document.write(num1 + 20 + '<br>'); //  30
        document.write((num1 + 20) + '<br>'); // 30 // 괄호 사용 권장!
        document.write(String(num1) + 20 + '<br>'); // 1020
    </script>

 

문자열 - 숫자 변환

    <script>
        var str1 = '10';
        document.write(str + typeof(str1) + '<br>');
        document.write(Number(str1) + ' ' + typeof(Number(str1)) + '<br>');
        document.write(parseInt(str1) + ' ' + typeof(parseInt(str1)) + '<br>');
        document.write(parseFloat(str1) + ' ' + typeof(parseFloat(str1)) + '<br>');

        // 실수 parse 방법 -> Int 빼고 사용 가능
        document.write(Number('123.412') + '<br>');
        document.write(parseInt('123.412') + '<br>');
        document.write(parseFloat('123.412') + '<br>');
    </script>

 

 

삼중등호(===) 연산자

- 데이터의 Type까지 비교하는 연산자
- JS에서 '==' 연산자는 type과 상관 없이 문자열(js 데이터 저장 구조)로 값이 일치하는지 확인 함
- 10 == "10" 일 경우 실제 저장 값이 "10"이므로 true가 나옴
    <script>
        document.write(10 == '10'); // true
        document.write('<br>');
        document.write(10 != '10'); // false
        document.write('<br>');

        // 삼중등호 연산자, type 같아야 true!
        document.write(10 === '10'); // false = type이 달라서
        document.write('<br>');

        document.write(10 !== '10'); // true type 같아서
        document.write('<br>');

        document.write(10 === 10); // type + 값이 같아서 true
        document.write('<br>');

        document.write(10 === 15); // type 같지만 값이 달라서 false
        document.write('<br>');
    </script>

 

문자열 연결 연산자

-문자열 연결은 연결 연산자 '+'를 사용합니다.

    <script>
        var str = "문자열 " + "연결은 " + "연결 연산자 " + " '+'" + "를 사용합니다.";
        document.write(str);
    </script>

 


"본 인터넷 사이트 내의 모든 이미지, 문구, 콘텐츠, 내용 등에 대한 저작권은 76beny에게 있습니다.

이를 무단으로 도용, 복사, 전재, 재배포, 2차 변형 등을 할 경우

민, 형사상 법적 조치 등 저작권법에 의거하여 처벌 받을 수 있습니다."