본문 바로가기

프로그래밍/Javascript

08_함수(2)

08_함수(2)

내장함수

1) alert 함수 : 매개인자로 받은 데이터를 경고창에서 보여줍니다.

2) document.write 함수 : 매개인자로 받은 데이터를 웹 브라우저에 출력합니다.

3) confirm 함수 : 매개인자로 받은 데이터를 confirm 창에서 보여주고, 사용자가 ‘확인’ 버튼을 클릭하면 true를, ‘취소’ 버튼을 클릭하면 false를 반환합니다.

4) prompt 함수 : 매개인자로 받은 데이터를 prompt 차에서 보여주고, text box에서 사용자 입력을 받습니다. 사용자가 입력한 값을 반환합니다.

전역변수와 지역변수

1) 전역 변수는 모든 함수에서 공유하는 변수입니다.

2) 지역 변수는 함수 내에서 선언된 변수로 함수 안에서만 사용할 수 있습니다.

실습예제

예제 08-1.html

confirm() 함수를 이용하여 사용자에게 18세 이상인지 물어보고, 18세 이상이면 '터미네이터 상영관으로 입장',

아니면 '텔레토비 상영관으로 입장' 메시지를 웹 브라우저 창에 출력하는 프로그램을 작성해 보겠습니다.

.another_category { border: 1px solid #E5E5E5; padding: 10px 10px 5px; margin: 10px 0; clear: both; } .another_category h4 { font-size: 12px !important; margin: 0 !important; border-bottom: 1px solid #E5E5E5 !important; padding: 2px 0 6px !important; } .another_category h4 a { font-weight: bold !important; } .another_category table { table-layout: fixed; border-collapse: collapse; width: 100% !important; margin-top: 10px !important; } * html .another_category table { width: auto !important; } *:first-child + html .another_category table { width: auto !important; } .another_category th, .another_category td { padding: 0 0 4px !important; } .another_category th { text-align: left; font-size: 12px !important; font-weight: normal; word-break: break-all; overflow: hidden; line-height: 1.5; } .another_category td { text-align: right; width: 80px; font-size: 11px; } .another_category th a { font-weight: normal; text-decoration: none; border: none !important; } .another_category th a.current { font-weight: bold; text-decoration: none !important; border-bottom: 1px solid !important; } .another_category th span { font-weight: normal; text-decoration: none; font: 10px Tahoma, Sans-serif; border: none !important; } .another_category_color_gray, .another_category_color_gray h4 { border-color: #E5E5E5 !important; } .another_category_color_gray * { color: #909090 !important; } .another_category_color_gray th a.current { border-color: #909090 !important; } .another_category_color_gray h4, .another_category_color_gray h4 a { color: #737373 !important; } .another_category_color_red, .another_category_color_red h4 { border-color: #F6D4D3 !important; } .another_category_color_red * { color: #E86869 !important; } .another_category_color_red th a.current { border-color: #E86869 !important; } .another_category_color_red h4, .another_category_color_red h4 a { color: #ED0908 !important; } .another_category_color_green, .another_category_color_green h4 { border-color: #CCE7C8 !important; } .another_category_color_green * { color: #64C05B !important; } .another_category_color_green th a.current { border-color: #64C05B !important; } .another_category_color_green h4, .another_category_color_green h4 a { color: #3EA731 !important; } .another_category_color_blue, .another_category_color_blue h4 { border-color: #C8DAF2 !important; } .another_category_color_blue * { color: #477FD6 !important; } .another_category_color_blue th a.current { border-color: #477FD6 !important; } .another_category_color_blue h4, .another_category_color_blue h4 a { color: #1960CA !important; } .another_category_color_violet, .another_category_color_violet h4 { border-color: #E1CEEC !important; } .another_category_color_violet * { color: #9D64C5 !important; } .another_category_color_violet th a.current { border-color: #9D64C5 !important; } .another_category_color_violet h4, .another_category_color_violet h4 a { color: #7E2CB5 !important; } \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var isAdult = confirm("18세 이상입니까?");
        if(isAdult == true){
            document.write("터미네이터 상영관으로 입장");
        } else {
            document.write("텔레토비 상영관으로 입장");
        }
    </script>
</head>
</html>

18세 이상

=> 확인

18세 이하

=> 취소

예제 08-2.html

prompt() 함수를 이용하여 점수를 3번 입력 받고, 점수의 합과 평균을 구하는 프로그램을 작성해 보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/39","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":39,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "9yelpLRtswrqFPsiN2i/x/VPgLoDeLzUj8qDlv4R3LV+iRlhY/JclPD6hpUAcmxj" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var jumsu = new Array();
        jumsu[0] = prompt("첫번째 점수를 입력하세요.","");
        jumsu[1] = prompt("두번째 점수를 입력하세요.","");
        jumsu[2] = prompt("세번째 점수를 입력하세요.","");
        
        var sum =0;
        for(var index in jumsu)
        {
            sum = sum+parseInt(jumsu[index]);
        }

        alert("점수 합은 "+sum+"평균은 "+ sum/jumsu.length+" 입니다.");
    </script>
</head>
</html>

예제 08-3.html

변수 영역에 대한 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/39","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":39,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "9yelpLRtswrqFPsiN2i/x/VPgLoDeLzUj8qDlv4R3LV+iRlhY/JclPD6hpUAcmxj" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var data=100; // 전역 변수 data를 선업하고 100으로 초기화
        function yourJob(){
            data=0; // 전역 변수 data를 사용
        }

        function myJob(){
            var data = 10; // 지역 변수 data를 선언하고 10으로 초기화
            data = data+ 100; // 지역 변수 data를 사용
        }
        
        yourJob(); // 전역변수 data의 값을 0으로 저장
        myJob(); // 전역변수를 사용하지 않음
        alert(data); // 전역변수 data의 값을 읽어 경고창에 보여줌
        // 전역변수 data의 값은 현재 0
    </script>
</head>
</html>

예제 08-4.html

함수를 여러 변수에 저장해보는 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/39","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":39,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "9yelpLRtswrqFPsiN2i/x/VPgLoDeLzUj8qDlv4R3LV+iRlhY/JclPD6hpUAcmxj" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function job(num){
            alert(num+"일 동안 영업 사원이 하는 일을 합시다");
            return ++num;
        }

        var hongGilDongJob = job;
        hongGilDongJob(job(100));
    </script>
</head>
</html>


'프로그래밍 > Javascript' 카테고리의 다른 글

10_이벤트와 이벤트 처리  (0) 2018.02.27
09_객체지향개념  (0) 2018.02.27
07_함수(1)  (0) 2018.02.27
06_배열  (0) 2018.02.27
05_반복  (0) 2018.02.27