ex) if문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> if문 </title>
<script>
var walkAmount = prompt("당신의 하루 걷는 양은 몇 보인가요?", "0");
if(walkAmount >= 10000) {
document.write("매우 좋은 습관을 지니고 계시는군요!!", "<br>");
}
document.write("=========== The End ===========");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> if문 </title>
<script>
var min = prompt("당신의 하루 통화량은 몇 분인가요?", "0");
if(min >= 60) { document.write("많이 사용하는 편이네요", "<br>"); }
document.write("===== The End ====");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> if문 </title>
<script>
var userName = prompt("방문자의 이름은?", "");
if(userName) {
document.write(userName+"님 반갑습니다! 방문을 환영합니다.");
}
</script>
</head>
<body>
</body>
</html>
ex) else문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> else문 </title>
<script>
var num = prompt("당신이 좋아하는 숫자는?", "0");
if(num % 2 == 0) {
document.write("당신이 좋아하는 숫자는 짝수입니다.");
} else {
document.write("당신이 좋아하는 숫자는 홀수입니다.");
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> else문 </title>
<script>
var result = confirm("정말로 회원을 탈퇴하시겠습니까?");
if(result) {
document.write("탈퇴 처리되었습니다!");
} else {
document.write("탈퇴 취소되었습니다!");
}
</script>
</head>
<body>
</body>
</html>
ex) else if문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> else if문 </title>
<script>
var mon = prompt("현재는 몇 월입니까?", "0");
if(mon >= 9 && mon <= 11){
document.write("독서의 계절 가을이네요!!");
}else if(mon >= 6 && mon <= 8){
document.write("여행 가기 좋은 여름이네요!!");
}else if(mon >= 3 && mon <= 5){
document.write("햇살 가득한 봄이네요!!");
}else{
document.write("스키의 계절 겨울이네요!!");
}
</script>
</head>
<body>
</body>
</html>
ex) 이중 if문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 중첩 if문 </title>
<script>
var id = "easy1004";
var pw = "112233";
var user_id = prompt("아이디는?","");
var user_pw = prompt("비밀번호는?","");
if(id == user_id) {
if(pw == user_pw) {
document.write(user_id+"님 반갑습니다!");
} else {
alert("비밀번호가 일치하지 않습니다.");
location.reload();
}
} else {
alert("아이디가 일치하지 않습니다.");
location.reload();
}
</script>
</head>
<body>
</body>
</html>
ex) switch문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택문 </title>
<script>
var site = prompt("네이버, 다음, 네이트, 구글 중 \
즐겨 사용하는 포털 검색 사이트는?", "");
var url;
switch(site){
case "구글": url = "www.google.com";
break;
case "다음": url = "www.daum.net";
break;
case "네이버": url = "www.naver.com";
break;
case "네이트": url = "www.nate.com";
break;
default: alert("보기 중에 없는 사이트입니다.");
}
if(url) location.href = "http://" + url;
</script>
</head>
<body>
</body>
</html>
ex) while문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> while문 </title>
<script>
var i = 1;
while( i <= 10 ) {
document.write("안녕하세요" + i, "<br />");
i++;
}
document.write("==== The End ====");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> while문 </title>
<script>
var i=1;
while( i <= 30 ) {
if( i % 2 == 0 && i % 6 == 0) {
document.write(i ,"<br />");
}
i++;
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> while문 </title>
<style>
*{margin: 0;}
.blue{color: #00f;}
.red{color: #f00;}
</style>
<script>
var i = 20;
while( i >= 10 ){
if( i % 2 == 0 ){
document.write("<p class='blue'>" + i + "</p>");
}else{
document.write("<p class='red'>" + i + "</p>");
}
i--;
}
</script>
</head>
<body>
</body>
</html>
ex) do while문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> do while문 </title>
<script>
var i = 10;
do {
document.write("hello!!");
} while ( i < 3 )
</script>
</head>
<body>
</body>
</html>
ex) for문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> for문 </title>
<script>
for( var i = 1; i <= 10; i++ ) {
sdocument.write("반복" + i, "<br>");
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> for문 </title>
<style>
*{margin: 0;}
.red{color: #f00;}
.green{color: #00f;}
.aqua{color: #0ff;}
</style>
<script>
for(var i = 1; i <= 100; i++){
if(i % 5 == 0 && i % 7 != 0) {
document.write("<p class='red'>"+i+"</p>");
} else if(i % 7 == 0 && i % 5 != 0) {
document.write("<p class='green'>"+i+"</p>");
} else if(i % 7 == 0 && i % 5 == 0) {
document.write("<p class='aqua'>"+i+"</p>");
}
}
</script>
</head>
<body>
</body>
</html>
ex) 이중for문 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 중첩for문 </title>
<script>
for(var i = 1; i <= 3; i++){
for(var k = 1; k <= 2; k++){
document.write(i + "행" + k + "열", "<br>");
}
document.write("<br>");
}
</script>
</head>
<body>
</body>
</html>
ex) break 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> break문 </title>
<script>
for(var i = 1; i <= 10; i++){
if(i == 6) break;
document.write(i, "<br>");
}
document.write("=== The End ===");
</script>
</head>
<body>
</body>
</html>
ex) continue 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> continue문 </title>
<script>
for(var i = 1; i <= 10; i++){
if( i % 2 == 0 ) continue;
document.write(i, "<br>");
}
document.write("=== The End ===");
</script>
</head>
<body>
</body>
</html>
ex) 사용자 정의 객체 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 사용자 정의 객체 </title>
<script>
var tv = new Object( );
tv.color = "white";
tv.price = 300000;
tv.info = function( ) {
document.write("tv 색상: " + this.color, "<br>");
document.write("tv 가격: " + this.price, "<br>");
}
var car = {
color: "black",
price: 5000000,
info: function( ) {
document.write("car 색상: " + this.color, "<br>");
document.write("car 가격: " + this.price, "<br>");
}
};
document.write("<h1>tv 객체 메서드 호출</h1>");
tv.info();
document.write("<h1>car 객체 메서드 호출</h1>");
car.info();
</script>
</head>
<body>
</body>
</html>
ex) 날짜 정보 객체
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 날짜 정보 객체 </title>
<script>
var today = new Date( );
var nowMonth = today.getMonth( ),
nowDate = today.getDate( ),
nowDay = today.getDay( );
document.write("<h1>오늘 날짜 정보</h1>");
document.write("현재 월: " + nowMonth, "<br>");
document.write("현재 일: " + nowDate, "<br>");
document.write("현재 요일:" + nowDay, "<br>");
var worldcup = new Date(2002, 4, 31);
var theMonth = worldcup.getMonth( ),
theDate = worldcup.getDate( ),
theDay = worldcup.getDay( );
document.write("<h1>월드컵 날짜 정보</h1>");
document.write("2002월드컵 몇 월: " + theMonth, "<br>");
document.write("2002월드컵 몇 일: " + theDate, "<br>");
document.write("2002월드컵 무슨 요일: " + theDay, "<br>");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 날짜 정보 객체 </title>
<script>
var today = new Date();
var nowYear = today.getFullYear();
var theDate = new Date(nowYear, 11, 31);
var diffDate = theDate.getTime( ) - today.getTime( );
var result = Math.ceil( diffDate / (60 * 1000 * 60 * 24) );
document.write("<h1>오늘부터 올해 연말까지 남은 날짜</h1>");
document.write("D-day: " + result + "일 남았습니다.");
</script>
</head>
<body>
</body>
</html>
ex) 수학객체 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 수학객체 </title>
<script>
var num = 2.1234;
var maxNum = Math.max(10, 5, 8, 30),
minNum = Math.min(10, 5, 8, 30),
roundNum = Math.round(num),
floorNum = Math.floor(num),
ceilNum = Math.ceil(num),
rndNum = Math.random( ),
piNum = Math.PI;
document.write(maxNum, "<br>");
document.write(minNum, "<br>");
document.write(roundNum, "<br>");
document.write(floorNum, "<br>");
document.write(ceilNum, "<br>");
document.write(rndNum, "<br>");
document.write(piNum, "<br>");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 수학객체 </title>
<script>
document.write("<h1>컴퓨터 가위, 바위, 보 맞추기</h1>");
var game = prompt("가위, 바위, 보 중 선택하세요?", "가위");
var gameNum;
switch(game) {
case "가위": gameNum = 1;
break;
case "바위": gameNum = 2;
break;
case "보": gameNum = 3;
break;
default: alert("잘못 작성하셨습니다.");
location.reload();
}
var com = Math.ceil( Math.random() * 3 );
document.write("<img src=\"images/math_img_" + com + ".jpg\">");
if(gameNum == com) {
document.write("<img src=\"images/game_1.jpg\">");
} else {
document.write("<img src=\"images/game_2.jpg\">");
}
</script>
</head>
<body>
</body>
</html>
ex) 배열객체 예시
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 배열객체 </title>
<script>
var arr = [30, "따르릉", true];
document.write("<h3>배열값 가져오기-1</h3>");
document.write(arr[0], "<br>");
document.write(arr[1], "<br>");
document.write(arr[2], "<br>");
document.write("<h3>배열값 가져오기-2</h3>");
for(var i = 0; i < arr.length; i++){
document.write(arr[i], "<br>");
}
document.write("<h3>배열값 가져오기-3</h3>");
for(i in arr){
document.write(arr[i], "<br>");
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 배열객체 </title>
<script>
var arr_1 = ["사당", "교대", "방배", "강남"];
var arr_2 = ["신사", "압구정", "옥수"];
var result = arr_1.join("-");
console.log(result);
result = arr_1.concat(arr_2);
console.log(result);
result = arr_1.slice(1, 3);
console.log(result);
arr_1.sort( );
console.log(arr_1);
arr_2.reverse( );
console.log(arr_2);
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 배열객체 </title>
<script>
var greenArr = ["교대", "방배", "강남"];
var yellowArr = ["미금","정자","수서"];
greenArr.splice(2, 1, "서초", "역삼"); // 2번 인덱스부터 1개의 데이터를 삭제. 그런 다음 "서초", "역삼"을 삽입
console.log(greenArr);
var data1 = yellowArr.pop( ); // yellowArr 배열 마지막 인덱스의 데이터를 빼어서 data1에 저장.
var data2 = yellowArr.shift( ); // yellowArr 배열 가장 앞쪽 인덱스의 데이터를 빼어서 data2에 저장.
yellowArr.push(data2); // data2에 저장된 데이터를 yellowArr 배열의 마지막 인덱스에 밀어 넣는다.
console.log(yellowArr);
yellowArr.unshift(data1); // data1에 저장된 데이터를 yellowArr 배열의 가장 앞쪽 인덱스에 밀어 넣는다.
console.log(yellowArr);
</script>
</head>
<body>
</body>
</html>
Q. 숫자 맞추기 게임
A.
- HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Number guessing game</h1>
<p>
We have selected a random number between 1 and 100. See if you can guess it in 10 turns or less. We'll tell you if your guess was too high or too low.
</p>
<label for="number">Enter a guess:</label>
<input type="text" id="number">
<input type="submit" id="submitBtn" value="Submit guess">
<p id="count"></p>
<p id="rightOrwrong"></p>
<p id="comment"></p>
<script src="NumberGuessingGame.js"></script>
</body>
</html>
- js
var randomNum = Math.floor(Math.random()*100)+1;
var numHistory = [];
var answer = "Wrong!";
var state = 0;
function game(){
var num = Number(document.getElementById("number").value);
console.log(num);
guessNumber(num);
numHistory.push(num);
console.log(numHistory.length);
printNumHistory();
printAnswer();
printGuessText();
document.getElementById("number").value = "";
document.getElementById("number").focus();
}
function guessNumber(num)
{
if(num>randomNum) state = 1;
else if(num<randomNum) state = -1;
else state = 0;
}
function printNumHistory(){
var str = "Previous guesses: "
for(var i=0;i<numHistory.length;i++)
str += numHistory[i] + " ";
document.getElementById("count").innerHTML = str;
}
function printAnswer(){
if(state != 0){
document.getElementById("rightOrwrong").innerHTML = "Wrong!";
document.getElementById("rightOrwrong").style.backgroundColor = "red";
}
else{
document.getElementById("rightOrwrong").innerHTML = "Congratulations! You got it right!";
document.getElementById("rightOrwrong").style.backgroundColor = "green";
}
}
function printGuessText(){
var str = "";
if(state == 1)
str = "Last guess was too high";
else if(state == -1)
str = "Last guess was too low";
else if(state == 0){
str = "<button onclick='newGame()'>Start new game</button>";
}
document.getElementById("comment").innerHTML = str;
}
function newGame(){
numHistory = [];
document.getElementById("count").innerHTML = "";
document.getElementById("rightOrwrong").innerHTML = "";
document.getElementById("comment").innerHTML = "";
}
document.getElementById("submitBtn").addEventListener('click', game);
728x90
'Web > javascript' 카테고리의 다른 글
[필기정리]Day51-2 - Hoisting, 자바스크립트 실습문제 등 (0) | 2020.09.04 |
---|---|
[필기정리]Day51-1 - 자바스크립트의 역사, use strict 등 (0) | 2020.09.03 |
[필기정리] Day50-1 - array sort, 유효성체크 (0) | 2020.08.31 |
[실습문제] JavaScript로 달력 만들기 (0) | 2020.08.19 |
[필기정리] Day48 - 단계별 달력 만들기 문제 등 (0) | 2020.08.19 |