📖
Javascript
  • 자바스크립트 시작하기
  • 자바스크립트 기초 문법
  • 변수
  • 배열
  • 객체
  • 연산자
  • 조건문
    • if 문
    • if ~ else 문
    • 다중 if문
    • 중첩 if문
    • switch 문
    • 삼항 연산자
  • 반복문
    • while 문
    • do while 문
    • for 문
    • 중첩 for 문
    • break 문
    • continue 문
  • 함수
    • 선언적 함수
    • 익명 함수
    • 매개변수가 있는 함수
    • Arguments 함수
    • 리턴값이 있는 함수
    • 재귀 함수
    • 콜백 함수
    • 내부 함수(스코프)
    • 객체 생성자 함수
    • 프로토타입 함수
    • 화살표 함수
    • 클래스
    • Promise
    • 함수 정리
    • 템플릿 리터럴
  • 내장객체
    • String 객체
      • split()
      • join()
    • Number 객체
    • Date 객체
    • Array 객체
    • Math 객체
    • 정규표현 객체
  • 브라우저 객체
    • Window 객체
    • Navigator 객체
    • Screen 객체
    • History 객체
    • Location 객체
  • 문서객체
  • 이벤트
Powered by GitBook
On this page
  • 리턴값이 있는 함수
  • 샘플 1 [리턴값이 있는 함수(결과)]
  • 샘플 2 [리턴값이 있는 함수(종료)]
  • 샘플 3 [리턴값 + 매개변수]
  • 샘플 4 [평균점수 구하기]
  • 샘플 5 [이미지 슬라이드]

Was this helpful?

  1. 함수

리턴값이 있는 함수

return문은 함수에서 결괏값을 반환할 때 사용합니다.(return=결과)

리턴값이 있는 함수

function 함수이름(){ //실행코드 return 리턴값; } let 변수 = 함수명 (); //함수호출

샘플 1 [리턴값이 있는 함수(결과)]

function func1(){
    let str = "함수가 실행되었습니다.";
    return str;
}
let value = func1();
document.write(value);

샘플 2 [리턴값이 있는 함수(종료)]

function func2(){
    document.write("함수가 출력되었습니다1.");
    return;
    document.write("함수가 출력되었습니다2.");
}
func2();
//함수가 출력되었습니다1. (break와 비슷. return 위에값만 출력)

샘플 3 [리턴값 + 매개변수]

function func3(num1, num2){
    //let sum = 0;
    //sum = num1 + num2;
    //document.write(sum);
    return num1 + num2;
}
let result = func3 (100,200);
document.write(result);

//300

샘플 4 [평균점수 구하기]

function testAvg(arrData){
    let sum = 0;
    for (let i = 0; i<arrData.length; i++){
        sum += Number(prompt(arrData[i] + "점수는?","0"));
        /*Number를 사용해서 물어본 값의 대답 입력한 값 전체 숫자로 인식*/
    }
    let avg = sum / arrData.length;
    return avg; /*평균값 리턴*/
}
let arrSubject = ["국어","수학"];
let result = testAvg(arrSubject);

document.write(result);
//배열+함수(for)
let arr1 = [100,200,300,400,500];
function avg(){

//배열안에 있는 데이터 값을 출력(for)
    for(let i=0; i<arr1.length; i++){
        document.write(arr1[i]);//100200300400500
    }
//배열안에 있는 데이터 값의 함을 출력 출력(for)
    let sum = 0;
    for( i=0; i<arr1.length; i++){
        sum = sum + arr1[i];
        //0 = 0 + 100
        //100=100+200
        //300=300+300
        //600=600+400
        //1000=1000+500
        //1500
    }
    document.write(sum); //1500
    document.write("<br>");

//배열안에 있는 데이터 값의 평균값(sum2)을 출력(for);
    let sum2 = 0;
    for (let i=0; i<arr1.length; i++){
        sum2 += arr1[i];
    }
    let avg2 = sum2 / arr1.length;
    document.write(avg2); //300
}
avg();

샘플 5 [이미지 슬라이드]

<body>
    <div id="gallery">
        <img id="img" src="img/pic_1.jpg" alt="이미지1" style="width: 300px;">
        <button class="prev">이전이미지</button>
        <button class="next">다음이미지</button>
    </div>
    <script>
        document.getElementById("img").setAttribute("alt", "학용품 이미지 입니다.");
        //속성값 alt="이미지1" ->  "학용품 이미지 입니다."변경
        
        //버튼을 클릭하면 경고창 출력
        let prev = document.querySelector(".prev");
        let next = document.querySelector(".next");//click 이벤트 변수화(= button onclick)
        let imge = document.getElementById("img");
        let num = 1;

        prev.addEventListener("click", function(){
            if( num == 1 ){
                alert("처음 이미지입니다.")
                return;
            }
            num--; // 순서중요
            imge.setAttribute("src","img/pic_" + num + ".jpg");
            console.log(num);
        });
        next.addEventListener("click", function(){
            if( num == 8){
                alert("마지막 이미지입니다.")
                return;
            }
            num++;
            imge.setAttribute("src","img/pic_" + num + ".jpg");
            console.log(num);
        });
    </script>
</body>

위에 겹치는 내용 함수화 시킨것이 아래 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="galleryZone">
        <p><img id="photo" src="img/pic_1.jpg" alt="이미지1" style="width: 500px"></p>
        <div>
            <button onclick="gallery(0)">이전</button>
            <button onclick="gallery(1)">다음</button>
        </div>
    </div>
    <script>
        let num = 1;
        function gallery(direct){
            if(direct){
                if(num == 8) {
                    return;//8 == 8이되면 다음 실행 안됨. 8까지만 출력.
                }
                num++; 
            } else {
                if (num == 1) {
                    return;//1 == 1이되면 다음 실행 안됨. 1까지만 출력.
                }
                num--;
            }
            console.log(num);
            let imgTag = document.getElementById("photo");
            imgTag.setAttribute("src","img/pic_"+ num +".jpg");
        }
    </script>
</body>
</html>
PreviousArguments 함수Next재귀 함수

Last updated 4 years ago

Was this helpful?