javascript 두번째

Park In Kwon·2022년 11월 29일
0

1. 유효범위(scope)

    <script>
        var vscope = 'global';

        function fscope(){
            alert(vscope);
        }
        function fscope2(){
            alert(vscope);
        }

        fscope();
        fscope2();
    </script>
    
     <script>
        var vscope = 'global';

        function fscope(){
            var lv = 'local val';
            alert(lv);
        }

        fscope();
        alert(lv);  // 오류발생
    </script>
    
     <script>
        /*
            같은 이름의 지역변수와 전역변수가 동시에 정의되어 있다면
            지역변수가 우선한다는 것을 알 수 있다.
        */
        var vscope = 'global';

        function fscope(){
            var vscope = 'local';
            alert('함수 안 ' + vscope);
        }

        fscope();
        alert("함수 밖 " + vscope);
    </script>
    
    <script>
        var vscope = 'global';

        function fscope(){
            vscope = 'local';
            alert('함수 안 ' + vscope);
        }

        fscope();
        alert('함수 밖 ' + vscope);
    </script>

2. var 변수 선언의 문제점

  • 동일한 변수명으로 선언하였음에도 불구하고, 에러가 나오지 않고 각각의 결과를
    출력해낸다.
  • 유연한 변수 선언으로 간단한 테스트에는 편리할 수 있으나, 코드량이 많아지면
    어디에서 어떻게 사용 될지 파악하기 힘들고, 버그 발생률이 높다.

2-1. 추가된 변수 선언 방식

  • let : 변수에 재할당이 가능

  • const : 변수 재선언, 재할당 모두 불가능

      <script>
          let name = 'html';
          console.log(name);
    
          let name = 'javascript';
          console.log(name);
      </script>
    
      <script>
          const name = 'html';
          console.log(name);
    
          const name = 'javascript';
          console.log(name);
      </script>

3. 배열

3-1. 배열을 만드는 법

let myarray = new Array(값1, 값2, ..., 값n);
let myarray = [값1, 값3, ..., 값n];

    <script>
        let myarray = ["HTML", "CSS", "javascript"];

        // 배열값 읽기
        document.write("<h1>" + myarray[0] + "</h1>");
        document.write("<h1>" + myarray[1] + "</h1>");
        document.write("<h1>" + myarray[2] + "</h1>");

        // 배열에 저장된 값 변경
        myarray[0] = "JAVA";
        myarray[1] = "JPS";
        myarray[2] = "Spring Boot";

        document.write("<h1>" + myarray[0] + "</h1>");
        document.write("<h1>" + myarray[1] + "</h1>");
        document.write("<h1>" + myarray[2] + "</h1>");
        document.write("<h1>--------------------</h1>");

        // 반복문을 통하여 배열 출력
        for( let i = 0; i<myarray.length; i++ ){
            document.write("<p>" + myarray[i] + "</p>");
        }

    </script>

3-2. 인덱스

  • 생성된 배열은 사물함과 같이 각각의 칸에 값들이 저장되고, 각각의 칸은 0부터
    일련번소가 지정된다.

     <script>
          let myarray = [
              ['HTML', 'CSS', "javascript"],
              ['JAVA','JSP','Spring']
          ];
    
          // 반복문, myarra 배열안의 항목 출력, 20분
          for( let i = 0; i<myarray.length; i++ ){
              for( let j = 0; j<myarray[i].length; j++ ){
                  document.write("<h1>" + myarray[i][j] + "</h1>");
              }
          }
      </script>

3-3. 배열 데이터 접근

  • 배열이름[인덱스]

      <script>
          // push() : 배열의 값을 추가
          let li = ['a', 'b', 'c', 'd'];
    
          li.push('e');
          document.write(li);
          document.write('<br>-----------------------<br>');
    
          // concat() : 배열의 값을 추가
          let li3 = ['a', 'b', 'c'];
          li3 = li3.concat(['d', 'e', 'f']);
          document.write(li3);
    
          document.write('<br>-----------------------<br>');
          // unshift() : 맨 앞에 배열의 값을 추가
          li3.unshift('zzz');
          document.write(li3);
    
      </script>

3-4. 2차배열

  • 배열이름[행][열]

    let myarray = new Array(
    new Array(값1, 값2, ..., 값n),
    new Array(값1, 값2, ..., 값n)
    );

    let myarray = [
    [값1, 값2, ..., 값n],
    [값1, 값2, ..., 값n]
    ];

    <script>
        let s = [
            '이유덕', '이재영', '권종표', '이재영', '박민호', '강상희',
            '이재영', '김지완', '최승혁', '이성연', '박영서',
            '박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌'
        ];

        // 1. "이재영"이라는 이름이 몇번 반복되는지?
        // 함수를 생성, "이재영" -> 파라미터로 넘겨받도록 
        function name( param ){
            let name = param;
            let count = 0;

            for( let i = 0; i<s.length; i++ ){
                if( s[i] == name ){
                    count++;
                }
            }

            return name + " : " + count;
        }

        document.write(name('이재영'));
        document.write('<br>');

        // 2. 중복된 이름을 제거한 이름을 출력
        // 결과 값 : 권종표,강상희,김지완,최승혁,이성연,박영서,송정환,김재성
        function name2(){
            let uniq = [];

            for( let i = 0; i<s.length; i++ ){
                let uni_cnt = 0;

                for( let j = 0; j<s.length; j++ ){
                    if( s[i] == s[j] ){
                        uni_cnt++;
                    }
                }

                if( uni_cnt < 2 ){
                    uniq.push(s[i]);
                }
            }

            return uniq;
        }
        
        document.write(name2());
        document.write('<br>');

    </script>

3-5. 길이

  • 행 : 배열이름.length;
  • 열 : 배열이름[n].length;

4. Math객체

    <script>
        // 절대값
        let num = -123;
        document.write("<h1>절대값 : " + Math.abs(num) + "</h1>");

        // 원주율
        document.write("<h1>원주율 : " + Math.PI + "</h1>");

        // 난수 발생
        document.write("<h1>난수 : " + Math.random() + "</h1>");

        // 소수점 반올림
        let num2 = 3.714567;
        document.write("<h1>반올림 : " + Math.round(num2) + "</h1>");

        // 소수점 올림/내림
        document.write("<h1>올림 : " + Math.ceil(num2) + "</h1>");
        document.write("<h1>내림 : " + Math.floor(num2) + "</h1>");
    </script>
    
     <script>
        // 1.Math.random() 사용해서 5자리 인증번호 생성, 출력
        // 00159, 45911, ..
        // function
        
        // 두 수 사이에 난수를 리턴하는 함수
        function random( n1, n2 ){
            return Math.floor(Math.random() * (n2 - n1 + 1)) + n1;
        }

        // 인증번호 5자리
        let auth = "";

        for( var i = 0; i<5; i++ ){
            auth += random(0,9);
        }

        document.write("<h1>인증번호 : " + auth + "</h1>");


        document.write("<br>-------------<br>");
        // 2. '가위', '바위', '보' -> 랜덤으로 출력
        // function
        let array = ['가위', '바위', '보'];

        function getGame(){
            let i = Math.floor(Math.random() * 3);
            document.write(array[i]);
        }

        getGame();

    </script>
profile
개발자로 진로 변경을 위해 준비하고 있습니다

0개의 댓글