CS Study/Javascript

4. 배열과 객체

Ryannn 2022. 4. 8. 13:00

1. 코어 객체 활용하기 - Date(), String()

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>객체 생성 및 활용</title>
</head>
<body>
	<h1>객체 생성 및 활용</h1>
	<hr>
	<script>
		let today = new Date();
		document.write("현재 시간 : "+today.toLocaleString()+"<br>");

		let mystr = new String("hello world");
		let str = "sadfasdga"
		document.write("mystr의 길이 : " + str.length + "<br>");
		document.write("mystr의 내용 : "+str);
	</script>

</body>
</html>

2. []로 배열 만들기

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>[]로 배열 만들기</title>
</head>
<body>
	<h1>[]로 배열 만들기</h1>
	<hr>
	<script>
		let plots = [20,5,8,15,20];
		document.write("let plots = [20,5,8,15,20]<br>");
		for(let i=0;i<plots.length;i++){
			let s = plots[i];
			while (s>0){
				document.write("*");
				s--
			}
			document.write(plots[i] + "<br>");
		}
	</script>

</body>
</html>

3. 평균 온도 출력 - Array 객체로 배열 만들기

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Array 객체로 배열 만들기</title>
</head>
<body>
	<h1>Array 객체로 배열 만들기</h1>
	<hr>
	<script>
		let temperature = new Array();
		for(let i =0;i<6;i++){
			temperature[i] = i*10;
		}
		let sum = 0;
		for(let i=0;i<temperature.length;i++){
			sum+=temperature[i];
		}
		document.write("평균 온도는 " + (sum/temperature.length));
	</script>

</body>
</html>

4. Array 객체의 메소드 활용

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Array 객체의 메소드 활용</title>
	<script>
		function pr(msg,array){
			document.write(msg + array.toString()+"<br>");
		}
	</script>
</head>
<body>
	<h1>Array 객체의 메소드 활용</h1>
	<hr>
	<script>
		let a = ["황", "김", "이"];
		let b = ["박"];
		pr("배열 a = ",a);
		pr("배열 b = ",b);
		document.write("<hr>");
		let c = a.concat(b);
		pr("c = a.concat(b)후 c = ",c);
		pr("c = a.concat(b)후 a = ",a);

		c = a.join("##");
		pr("c = a.join()후 c = ",c);
		pr("c = a.join()후 a = ",a);

		c = a.reverse();
		pr("c = a.reverse()후 c = ",c);
		pr("c = a.reverse()후 a = ",a);

		c = a.slice(1,2);
		pr("c = a.slice(1,2)후 c = ",c);
		pr("c = a.slice(1,2)후 a = ",a);

		c = a.sort();
		pr("c = a.sort()후 c = ",c);
		pr("c = a.sort()후 a = ",a);

		c = a.toString();
		document.write("a.toString() : "+ c);

	</script>


</body>
</html>

5. Date() 객체로 현재 시간 알아내기

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>date 객체로 현재시간 알아내기</title>
</head>
<body>
	<h1>Date객체로 현재 시간 알아내기</h1>
	<hr>
	<script>
		let date = new Date();
		document.write("현재 시간 : " + date.toUTCString());
		document.write("<hr>");
		document.write(date.getFullYear() + "년도<br>");
		document.write(date.getMonth()+1 + "월<br>");
		document.write(date.getDate() + "일<br>");
		document.write(date.getHours() + "시<br>");
		document.write(date.getMinutes() + "분<br>");
		document.write(date.getSeconds() + "초<br>");
		document.write(date.getMilliseconds() + "밀리초<br>");
		document.write("<hr>");
		let next = new Date(2023,7,15,12,12,12);
		document.write("next.toLocaleString() : " + next.toLocaleString());

	</script>

</body>
</html>

6. 방문 시간에 따라 변하는 배경색 - Date()객체 활용

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>방문 시간에 따라 변하는 배경색</title>
</head>
<body>
	<h1>페이지 방문 초시간이 짝수이면 violet, 홀수이면 lightskyblue 배경</h1>
	<hr>
	<script>
		let date = new Date();
		document.write("현재 시간 : " + date.toUTCString());
		if(date.getSeconds()%2 == 0){
			document.body.style.background = "violet";
		}
		else{
			document.body.style.background = "lightskyblue";
		}
	</script>

</body>
</html>

7. String() 객체의 메소드 활용

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>string 객체의 메소드 활용</title>
</head>
<body>
	<h1>string 객체의 메소드 활용</h1>
	<hr>
	<script>
		let a = "Boys and Girls";
		let b = "!!";
		document.write("a : " + a + "<br>");
		document.write("b : " + b + "<br>");
		document.write("<hr>");
		document.write(a.charAt(0)+ "<br>");
		document.write(a.concat(b,"입니다")+ "<br>");
		document.write(a.indexOf("s")+ "<br>");
		document.write(a.indexOf("S")+ "<br>");
		document.write(a.slice(5,8)+ "<br>");
		document.write(a.substr(5,3)+ "<br>");
		document.write(a.toUpperCase()+ "<br>");
		document.write(a.toLowerCase()+ "<br>");
		document.write(a.replace("and","or")+ "<br>");
		let sub = a.split(" ");
		document.write("<hr>");
		document.write("a를 빈칸으로 분리"+ "<br>");
		for(let i=0;i<sub.length;i++){
			document.write("sub[" +i+"] : " + sub[i]+ "<br>");
		}
		document.write("<hr>");
		document.write("String 메소드를 실행 후 a와 b 변함없음"+ "<br>");
		document.write("a : " + a+ "<br>");
		document.write("b : " + b+ "<br>");
	</script>

</body>
</html>

8. 구구단 계산 - Math 활용

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Math를 활용한 구구단 연습</title>
	<script>
		function getrandomInt(){
			let a = Math.random()*10;
			let m = Math.floor(a);
			return m;
		}
	</script>
</head>
<body>
	<h1>Math를 활용한 구구단 연습</h1>
	<hr>
	<script>
		let n1 = getrandomInt();
		let n2 = getrandomInt();
		let question = n1 + "*"+ n2 + "값은 얼마입니까?";
		let answerUser = prompt(question);
		answerUser = parseInt(answerUser);
		if(answerUser == (n1*n2)){
			document.write("정답! " + n1 + "*" + n2 + "=" + answerUser + "입니다");
		}
		else{
			document.write("땡 바보멍충이~");
		}
	</script>

</body>
</html>

9. 사용자 객체 만들기 - new Object() 활용

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>new Object()로 사용자 객체 만들기</title>
	<script>
		function inquiry(){
			return this.balance;
		}
		function deposit(money){
			this.balance += money;
		}
		function withdraw(money){
			this.balance -= money;
		}

		let account = new Object();
		account.owner = "황기태";
		account.code = "111";
		account.balance = 35000;
		account.inquiry = inquiry;
		account.deposit = deposit;
		account.withdraw = withdraw;
	</script>
</head>
<body>
	<h1>new Object()로 사용자 객체</h1>
	<hr>
	<script>
		document.write("account : " + account.owner +", " + account.code +", " + account.balance + "<br>");
		account.deposit(10000);
		document.write("10000원 저금 후 잔액은 " + account.inquiry() +"<br>");
		account.withdraw(5000);
		document.write("5000원 출금 후 잔액은 "+account.inquiry() + "<br>");
	</script>


</body>
</html>

10. 계좌 내역 출력하기 - new Object() 활용

<!DOCTYPE html>
<html lang="ko">
<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>
        let account = {
            owner : "황기태",
            code : "111",
            balance : 35000,

            inquiry : function(){
                return this.balance;
            },
            withdraw : function(money){
                this.balance-=money;
            },
            deposit : function(money){
                this.balance+=money;
            }

        }
    </script>
</head>
<body>
    <h1>new Object()로 사용자 객체</h1>
	<hr>
	<script>
		document.write("account : " + account.owner +", " + account.code +", " + account.balance + "<br>");
		account.deposit(10000);
		document.write("10000원 저금 후 잔액은 " + account.inquiry() +"<br>");
		account.withdraw(5000);
		document.write("5000원 출금 후 잔액은 "+account.inquiry() + "<br>");
	</script>
    
</body>
</html>

11. 계좌 내역 출력하기 - Prototype 활용

<!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>
        function Account(owner,code,balance){
            this.owner = owner;
            this.code = code;
            this.balance = balance;
            this.inquiry  = function(){
                return this.balance;
            }
            this.deposit = function(money){
                this.balance+=money;
            }
            this.withdraw = function(money){
                this.balance-=money;
            }
        }
    </script>
</head>
<body>
    <h1>account 프로토타입 만들기
    </h1>
    <hr>
    <script>
        let account = new Account("황기태","111", 35000);
        document.write("account : " + account.owner +", "+ account.code +", "+ account.balance + "<br>");
        account.deposit(5000);
        document.write("10000원 저금 후 잔액은 " + account.inquiry()+ "<br>");
        account.withdraw(10000);
        document.write("5000원 출금 후 잔액은 " + account.inquiry());
    </script>
    
</body>
</html>

12. 사전 순으로 이름 정렬하기 - Array 객체의 sort() 메소드 활용

<!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>
        let names = new Array("wonsun","jaemoonlee","kitae","gracehwang");
        names.sort();
        for(let i = 0;i<names.length;i++){
            document.write(names[i] + " ");
        }
    </script>
</body>
</html>

13. 16개의 랜덤한 색 만들기 - Math.random() 활용

<!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>
    <style>
        div{
            display : inline-block;
            width : 150px;
            padding : 10px;
        }
    </style>
</head>
<body>
    <h1>16개의 랜덤한 색 만들기</h1>
    <hr>
    <script>
        for(let i =0;i<16;i++){
            let colorR = Math.floor(Math.random()*256);
            let colorG = Math.floor(Math.random()*256);
            let colorB = Math.floor(Math.random()*256);
            document.write("<div style = \"background : rgb(" +colorR+","+colorG+","+colorB+")"+ "\" >" + "rgb(" + colorR+","+colorG+","+colorB+")"+"</div>");
        }
    </script>
    
</body>
</html>

14. 최고가 책 이름 출력하기 - 객체 배열 활용

<!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>
    <h1>book 객체 배열 만들기</h1>
    <hr>
    <script>
        let bookArray = new Array();
        let expensive = 0;
        let expensiveName= "";
        for(let i =0;i<5;i++){
            bookArray[i] = prompt("콤마로 분리하면서 책제목 저자 가격 순으로 입력");
            let s = bookArray[i].split(",");
            let book = new Object();
            book.title = s[0];
            book.author = s[1];
            book.price = parseInt(s[2]);
            document.write(book.title +"," + book.author+"," + book.price + "<br>");
            if(book.price > expensive){
                expensive = book.price;
                expensiveName = book.title;
            }
        }
        document.write("<hr>");
        document.write("가장 가격이 비싼 책은 " + expensiveName);
    </script>

</body>
</html>