728x90
반응형
SMALL
# 두가지 방식의 함수 선언과 호출
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
var count = 0;
myFnc();
function myFnc() {
count++;
document.write("hi"+count, "<br>");
}
myFnc();
var theFunc = function() { //익명함수
count++;
document.write("bye"+count, "<br>");
}
theFunc();
</script>
</body>
</html>
# 배경바꾸기 버튼 클릭 시마다 배경색이 바뀌는 함수
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<script>
var color = ["white", "yellow", "aqua", "purple"];
var i = 0;
function changeColor() {
i++;
if(i>=color.length) {
i = 0; //4이상이면 다시 0으로 돌아가 반복
}
var bodyTag = document.getElementById("theBody");
//id 값이 theBody인 요소 선택
bodyTag.style.backgroundColor = color[i];
//bodyTag라는 요소의 배경색을 color[i]로
}
</script>
</head>
<body id="theBody">
<button onclick="changeColor();">배경색 바꾸기</button>
<!--버튼을 클릭하면 changeColor() 함수 호출-->
</body>
</html>
# 매개변수가 있는 함수 정의문
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
function F1(name, area) {
document.write("이름은 "+name+"입니다.", "<br>");
document.write("지역은 "+area+"입니다.", "<br>");
document.write("================", "<br>")
}
F1("홍당무", "부산");
F1("당근", "서울");
</script>
</body>
</html>
# 아이디 비번 입력 검증
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
var rightId = "happyday";
var rightPw = "1234";
function check(id, pw) {
if(id == rightId) {
if(pw == rightPw) {
document.write("로그인이 되었습니다.");
} else {
alert("비번이 틀렸습니다.");
}
} else {
alert("아이디가 틀렸습니다.");
}
}
var userId = prompt("id를 입력하세요.", "");
var userPw = prompt("pw를 입력하세요.", "");
check(userId, userPw);//이렇게 호출해서 userId와 userPw 검토
</script>
</body>
</html>
# 과목별 성적을 받아서 평균값을 return으로 반환
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
function testAvg(arrData) {
var sum = 0;
for(var i=0; i<arrData.length; i++) {
sum+=Number(prompt(arrData[i]+"의 점수는?", "0"));
}
var avg = sum / arrData.length ;
return avg;
}
var arrSubject = ["국어", "수학", "영어"];
var result = testAvg(arrSubject);
document.write("평균점수는 "+result+"점 입니다.");
</script>
</body>
</html>
# 갤러리 만들기
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<script>
var num = 1;
function gallery(direct) {
if(direct) { //다음 누르면 direct=1 if(true)
if(num==8) return; //num=8 나오면 종료.이미지가 8까지 있어서.
num++;
} else { //이전 누르면 direct=0 if(false)
if(num==1) return; //num=1 나오면 종료. 더 앞이 없음.
num--;
}
var imgTag = document.getElementById("photo");
//id 값이 photo인 이미지 태그 선택
imgTag.setAttribute("src", "images/pic_"+num+".jpg");
//setAttribute("속성명", "새 값") 선택한 태그의 지정한 속성을 새 값으로 바꿈
}
</script>
</head>
<body>
<div id="galleryZone">
<p><img src="images/pic_1.jpg" id="photo" alt=""></p>
<p>
<button onclick="gallery(0)">이전</button>
<!--클릭시 gallery(0) 함수 실행-->
<button onclick="gallery(1)">다음</button>
<!--클릭시 gallery(1) 함수 실행-->
</p>
</div>
</body>
</html>
# 재귀함수
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
var num = 0;
function testF() {
num++;
document.write(num, "<br>");
if(num==10) return;
testF();
}
testF();
</script>
</body>
</html>
# 즉시 실행 함수
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
(function() {
var num = 100;
function menu() {
num+= 100;
alert(num);
}
menu();
}());
(function() {
var num = 100;
function menu() {
alert(num);
}
}());
</script>
</body>
</html>
# 객체 생성자 함수
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
function CheckWeight(name, height, weight) {
this.userName = name; //this.속성명 = 새 값;
this.userHeight = height;
this.userWeight = weight;
this.minWeight;
this.maxWeight;
this.getInfo = function() {
var str = ""
str += "이름: "+this.userName+", ";
str += "키: "+this.userHeight+", ";
str += "몸무게: "+this.userWeight+"<br>";
return str;
}
this.getResult = function() {
this.minWeight = (this.userHeight - 100)*0.9-5;
this.maxWeight = (this.userHeight - 100)*0.9+5;
if(this.userWeight >= this.minWeight && this.userWeight <= this.maxWeight) {
return "정상 몸무게 입니다.";
} else if(this.userWeight < this.minWeight) {
return "저체중 입니다."
} else {
return "과체중 입니다."
}
}
}
var jang = new CheckWeight("장보리", 168, 53);//jang 객체 생성
var kim = new CheckWeight("박달재", 184, 60);//kim 객체 생성
console.log(jang);
console.log(kim);
document.write(jang.getInfo());
document.write(jang.getResult());
document.write("-----------------------", "<br>");
document.write(kim.getInfo());
document.write(kim.getResult());
</script>
</body>
</html>
# 프로토 타입으로 함수 등록
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
function CheckWeight(name, height, weight) {
this.userName = name; //this.속성명 = 새 값;
this.userHeight = height;
this.userWeight = weight;
this.minWeight;
this.maxWeight;
}
CheckWeight.prototype.getInfo = function() {
var str = ""
str += "이름: "+this.userName+", ";
str += "키: "+this.userHeight+", ";
str += "몸무게: "+this.userWeight+"<br>";
return str;
}
CheckWeight.prototype.getResult = function() {
this.minWeight = (this.userHeight - 100)*0.9-5;
this.maxWeight = (this.userHeight - 100)*0.9+5;
if(this.userWeight >= this.minWeight && this.userWeight <= this.maxWeight) {
return "정상 몸무게 입니다.";
} else if(this.userWeight < this.minWeight) {
return "저체중 입니다."
} else {
return "과체중 입니다."
}
}
var jang = new CheckWeight("장보리", 168, 53);
var kim = new CheckWeight("박달재", 184, 60);
console.log(jang);
console.log(kim);
document.write(jang.getInfo());
document.write(jang.getResult());
document.write("-----------------------", "<br>");
document.write(kim.getInfo());
document.write(kim.getResult());
document.write(jang.getResult === kim.getResult);
//두 객체가 같은 함수를 사용하고 있다는 의미??**
</script>
</body>
</html>
# 퀴즈1
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 함수 </title>
<script>
function test(){
var arrColor = ["#ff0", "#6c0", "#fcf", "#cf0", "#39f"];
var arrNum = Math.floor(Math.random()*arrColor.length);
var bodyTag = document.getElementById("theBody");
bodyTag.style.backgroundColor=arrColor[arrNum];
}
</script>
</head>
<body id="theBody">
<button onclick="test()">배경 색상 바꾸기</button>
</body>
</html>
# 퀴즈2
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 함수 </title>
<script>
function TestScore(name, kor, eng){
this.userName = name;
this.korNum = kor;
this.engNum = eng;
}
TestScore.prototype.getTestInfo = function() {
document.write("이름: " +this.userName, "<br>");
document.write("국어: " +this.korNum, "<br>");
document.write("영어: " +this.engNum, "<br>");
}
TestScore.prototype.getAvg = function() {
return (this.korNum+this.engNum) / 2;
}
var kimgun = new TestScore("김군",80,90);
var ohgun = new TestScore("오군",100,80);
kimgun.getTestInfo();
document.write("평균 점수:" + kimgun.getAvg(), "<br><br>");
ohgun.getTestInfo();
document.write("평균 점수:" + ohgun.getAvg(), "<br>");
</script>
</head>
<body>
</body>
</html>
출처 : doit javascript
728x90
반응형
LIST
'JAVASCRIPT' 카테고리의 다른 글
Javascript Jquery Selector 자바스크립트 제이쿼리 선택자 2 (0) | 2022.05.09 |
---|---|
Javascript Jquery Selector 자바스크립트 제이쿼리 선택자 1 (0) | 2022.05.08 |
Javascript Browser Object Model 자바스크립트 브라우저 객체 모델 (0) | 2022.05.08 |
Javascript Built in Object - String Object, 자바스크립트 내장객체 - 문자열객체 (0) | 2022.05.07 |
Javascript Built in Object - Math Object 자바스크립트 내장객체 - 수학객체 (0) | 2022.05.06 |