리턴값이 있는 함수
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>
Last updated
Was this helpful?