Programming/국비학원

220630 - 자바스크립트 - 반복문, 함수, 객체

지고르 2022. 7. 1. 09:46
반복문
  • 중첩 for문
  •  

    <script>
        for (var i=1;i<=5;i++){
            for (var j=1;j<=5;j++){
                document.write(i+"    "+j+"<br>");
            }
        }
    </script>

 

 

  •  

    <script>
        for (var i=1;i<=5;i++){
            document.write("우리모두 ");
            for(var j=1;j<=3;j++){
                document.write("아자 ");
            }
            document.write("화이팅<br>");
        }
    </script>

//
우리모두 아자 아자 아자 화이팅
우리모두 아자 아자 아자 화이팅
우리모두 아자 아자 아자 화이팅
우리모두 아자 아자 아자 화이팅
우리모두 아자 아자 아자 화이팅

 

 

  • 하이퍼링크 html에 추가

    <script>
        var na=['서울방송','한국방송','문화방송','교육방송'];
        var url=['www.sbs.co.kr','www.kbs.co.kr','www.imbc.com','www.ebs.co.kr'];
        for (var i=0;i<na.length;i++){
            document.write("<h1><a href='http://"+url[i]+"''>"+na[i]+"</a></h1>");
        }
    </script>

 

 

  • 문제 : 구구단

    <style>
        h2{
            text-align: center;
        }
        .gugu{
            display: inline-block;
            margin: 20px;
            border: 1px solid #ccc;
            padding: 0 20px 30px 20px;
            box-shadow: 1px 2px 1px rgba(0,0,0,0.5);
            line-height: 1.2;
        }
        .gugu:hover{
            background-color: beige;
        }
        .gugu h3{
            text-align: center;
        }
    </style>
    <script>
        document.write("<h2>구구단</h2>");
        for (var i=2;i<=9;i++){
            document.write("<div class='gugu'><h3>"+i+"단</h3>");
            for(var j=1;j<=9;j++){
                if (i*j>=10){
                    document.write(i+" X "+j+" = "+(i*j)+"<br>");
                } else{
                    document.write(i+" X "+j+" =&nbsp;&nbsp;"+(i*j)+"<br>");
                }
            }
            document.write("</div>");
        }        
    </script>

 

 

  • while문

데이터 처리 시 자주 사용 (데이터 수 미정일 때)
무한루프 주의

 

 

  • 문제 : 문장 10번 출력하기

    <script>
        var count=1;    //while문 바깥
        while(count<=10){
            document.write("비가 옵니다.<br>");
            count++;
        }
    </script>

 

 

  • 문제 : 1부터 100사이의 3의 배수 찾기, 갯수 세기

        document.write("<h2>3의 배수 찾기</h2>");
        var cnt=1;
        var num=0;
        while(cnt<=100){
            if (cnt%3==0){
                document.write(cnt+", ");  //3의 배수들
                num++;  //3의 배수 조건 참인 경우
            }
            cnt++; 
        }
        document.write("<br><br><br>1부터 100 사이의 3의 배수의 개수 : "+num);

 

 

 

  • 문제 : if문으로 -1 발견될때까지반복

    <script>
        var nums=[57,63,15,96,36,71,-1,36,74];
        var sum=0;
        var i=0;
        while(true){   //원래는 while(i<nums.length){
            sum+=nums[i];
            i++;
            if (nums[i]==-1){  //= 하나만 입력해서 오류 발생했었음..
                break;
            }
        }
        document.write(sum+"<br>");
        document.write(i);
    </script>    

 

 

  • do while

while 조건 부합하지 않아도 do문 1회 필수 수행

 

  •  

        var k=0;
        do{
            document.write("<br>비가 옵니다. 계속..");
            k++;
        } while(k>=5);

 

 

  • continue

반복문에서 수행하지 않을 특정 조건 지정

 

 

  • 문제 : 배열에서 짝수의 합만 구하기 (배열의 크기만큼 반복문 수행)

    <script>
        var nums=[36,23,67,99,87,66,74,28,96,57];
        var sum=0;
        for(var i=0;i<nums.length;i++){
            if (nums[i]%2!=0){  //==1
                continue;
            }
            sum+=nums[i];
        }
        document.write(sum);
    </script>

 

 

 

함수
  • 사용자 정의 함수
  • 매개변수 X
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>함수</title>
    <script>
        function hello(){
            alert("안녕하세요");
        }
        </script>
</head>
<body>
    <h1 onclick="hello();">함수 호출</h1>  
//호출하면 함수 수행  //이벤트: mouseout, mousein, hover, dbl
</body>
cs

 

 

  • 매개변수 O
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>함수</title>
    <script>
        function hello(na){
            alert(na+"님 안녕하세요");
        }
        function addNum(a,b){
            alert("두 수의 합은 = "+ (a+b));  //a, b 괄호 필수 (문자 인식되기 때문)
        }
        </script>
</head>
<body>
    <h1 onclick="hello('김철수');">함수 호출</h1>
    <button onclick="addNum(35,15);">더하기</button>
</body>
cs

 

 

※ 함수 호출 관련

 

    <script>
        hello('hello');
        function hello(na){
            alert(na+"님 안녕하세요");
        }
        function addNum(a,b){
            alert("두 수의 합은 = "+ (a+b)); 
        }
        hello('bye');
    </script>

 

=> hello function 생성했기 때문에 내장함수화
=> 내장화되면 사용자지정함수의 앞, 뒤 위치와 상관없이 코드 입력하면 수행됨

 

 

  • 리턴값 O

    <script>
        var num1=Number(prompt("첫번째 숫자를 입력해주세요."));
        var num2=Number(prompt("두번째 숫자를 입력해주세요."));
        // addNum(num1,num2);
        // function addNum(a,b){
        //     var sum=a+b;
        //     alert("두 수를 더한 값은 "+sum+"입니다");
        // }
        var result=addNum(num1,num2);
        alert("두 수를 더한 값은 "+result+"입니다.");
        function addNum(a,b){
            var sum=a+b;
            return sum; 
        }
    </script>

 

 

  • 사용자 정의 함수 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>사용자 정의 함수 예제</title>
    <style>
        #pet{
            width: 430px;
            border: 1px solid #ccc;
            margin: auto;
            padding: 15px;
            position: relative;
        }
        button{
            border: 1px solid #ccc;
            padding: 5px;
            background-color: rgba(255,255,255,0.7);
        }
        .over{
            position: absolute;
            left: 30px;
            bottom: 30px;
        }
        .detail{
            width: 420px;
            text-align: justify;
            line-height: 1.8;
            display: none;
        }
        .close{
            position: absolute;
            left: 330px;
            bottom: 30px;
        }
    </style>
    <script>
        window.onload = function(){ //desc 생성 전 -> 대응 1.body 2.window.onload
            var desc=document.querySelector("#desc");  
           
            var op=document.querySelector("#op");
            op.onclick=function(){
                op.style.border="2px solid blue";
            }
            op.ondblclick=function(){
                desc.style.display="block";
                op.style.display="none";
                op.style.border="none";
            }
 
            var sp=document.querySelector("#shepherd");
            sp.onmouseover=function(){
                sp.style.border="5px solid red";
                sp.style.transition="border 0.5s";  //transition=>hover만 고려해 click에 적용 불가
            }
            sp.onmouseout=function(){
                sp.style.border="none";
                // sp.style.transition="border 1s"  
            }
        }
 
       //function showDetail(){
       //    desc.style.display="block";
       //    op.style.display="none";
       //}
 
        function hideDetail(){
            desc.style.display="none";
            op.style.display="block";
        }
    </script>
</head>
<body>
    <div id="pet">
        <img src="../images/shepherd.jpg" alt="" id="shepherd">
        <button class="over" id="op">상세설명보기</button>
        <div id="desc" class="detail">
            <h3>shepherd</h3>
            <p>초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..
                초기에 독일에서 목양견으로 활약하던 이 개는 능력을 인정받아..</p>
            <button class="close" onclick="hideDetail();">상세설명닫기</button>
        </div>
    </div>
</body>
cs

 

 

 

  • 내장 함수

alert, prompt, confirm, ...

 

 

  • setTimeout : x초 지나면 1회 수행

    <script>
        setTimeout(function(){
            alert("3초가 지났습니다");
        },3000);
    </script>

 

 

  • setInterval : x초마다 수행

    <script>
        setInterval(function(){
            alert("hello");
        },3000);
    </script>

 

 

  • eval : 문자열을 자바스크립트 코드로 인식

    <script>
        var str="";
        str+="var age=25;";
        str+="var na='홍길동';";
        str+="alert(na+'님 나이가 '+age+'세이군요');";
        eval(str);
    </script>

 

 

 

객체
  • 객체 속성값 출력

1. 객체명.속성이름

2. 객체명['속성이름']

 

 

  •  

    <script>
        //배열 참고
        /*var fruits=['사과','딸기','수박','자두','바나나'];
        for (var i in fruits){
            document.write(fruits[i]);
        }
        alert(fruits[0]);*/

        var product={   //객체 생성
            //속성이름:속성값;    
            제품명:'건조 망고',
            유형:'당절임',
            가격:3500,
            원산지:'필리핀'
        };
        alert(product.가격);
        alert(product.가격*210);  //연산 가능
        alert(product['제품명']);  //'',"" 필수 => 제외하면 변수로 인식

        var na = '유형';
        alert(na);  //유형

        var 가격='제품명';
        alert(product[가격]);  //건조망고
        alert(product['가격']);  //3500

        for (var key in product){
            document.write("★"+key+" => "+ product[key]);
        }
    </script>

 

//

 

★제품명 => 건조 망고
★유형 => 당절임
★가격 => 3500
★원산지 => 필리핀