Web/javascript

JavaScript 제어문, 배열, 배열 반복, 함수, 객체1

dustKim 2024. 4. 16. 21:16
제어문
조건문
  • if 문
# 사용 방법

if(조건식){
    조건식의 결과가 true일 때 실행할 문장;
    ...
}
--------------------------------------------

if(조건식){
    조건식의 결과가 true일 때 실행할 문장;
    ...
}else{
    조건식의 결과가 false일 때 실행할 문장;
}
---------------------------------------------

if(조건식1){
    조건식1의 결과가 true일 때 실행할 문장;
    ...
}else if(조건식2){
    조건식2의 결과가 true일 때 실행할 문장;
    ...
}else{
    모든 조건식의 결과가 false일 때 실행할 문장;
    ...
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>if 문</title>
</head>
<body>
    <h2>if 문</h2>
    <script>
        const age = Number(prompt("나이를 입력하세요"));

        if(age > 19){
            console.log("성인입니다.");
        }else if(age > 14){
            console.log("청소년입니다.")
        }else if(age > 6){
            console.log("어린이입니다.")
        }else{
            console.log("유아입니다.")
        }
    </script>
</body>
</html>
결과

 

  • switch 문
# 사용 방법

switch(변수 또는 값) {
    case 값1:
        변수와 값1이 같은 경우 실행할 문장;
        ...
        break;
    case 값2:
        변수와 값2가 같은 경우 실행할 문장;
        ...
        break;
    ...
    default:
        변수와 모든 값이 다를 경우 실행할 문장;
        ...
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>switch 문</title>
</head>
<body>
    <h2>switch 문</h2>
    <script>
        let input = prompt("아동, 청소년, 성인 중 하나를 고르세요.");

        switch(input){
            case "아동":
                input += ": 입장료 무료";
                break;
            case "청소년":
                input += ": 입장료 5,000원";
                break;
            case "성인":
                input += ": 입장료 10,000원";
                break;
            default:
                alert("입력값을 확인하세요!");
                input = "입력값 확인";
        }
        console.log(input);
    </script>
</body>
</html>
결과

 

반복문
  • while 문
# 사용 방법

while(조건식) {
    조건식의 결과가 true인 동안 반복할 문장;
    ...
}

-------------------------------------------

do {
    조건식의 결과가 true인 동안 반복할 문장;
    ...
}while(조건식);

- do ~ while 문은 조건식의 결과가 처음부터 false인 경우라도 한 번은 {}의 문장을 실행함
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>while 문</title>
</head>
<body>
    <h2>while 문</h2>
    <script>
        while(true) {
            let num = Number(prompt("숫자를 입력하세요"));
            if (num % 2 == 0) {
                console.log("짝수입니다. 프로그램을 종료합니다.");
                break;
            };
            console.log("홀수입니다. 계속 진행하세요");
        }
    </script>
</body>
</html>
결과

 

  • for 문
# 사용 방법

for(초기값; 조건식; 증감식;) {
    조건식의 결과가 true인 동안 반복할 문장;
    ...
}

------------------------------------------

for문의 무한루프
for(;;) {
    ...
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>for 문</title>
</head>
<body>
    <h2>for 문</h2>
    <script>
        for(let i=1; i<=100; i++) {
            console.log(i);
        };
    </script>
</body>
</html>
결과

 

  • break 문

- switch 문 또는 반복(while, for)중인 루프 내에서 사용하여 해당 문장을 완전히 종료시키고 다음에 위치한 실행문으로 이동한다.(while 문 예제 참고)

 

  • continue 문

- 반복중인 루프 내에서 사용하여 해당 루프의 나머지 부분을 건너뛰고 다음 반복문의 실행으로 넘어간다.

# 사용 방법

let num = 값;
while(num <= 값) {
    console.log(num);
    num++;
    if (num == 특정값) continue;
    ...
    ...
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>for 문</title>
</head>
<body>
    <h2>for 문</h2>
    <script>
        for(let i=1; i<=100; i++) {
            if (i % 3 == 0) {
                console.log('😀');
                continue;
            };
            console.log(i);
        };
    </script>
</body>
</html>
결과

 


 

배열
배열(Array)

- 이름과 인덱스로 참조되는 정렬된 값의 집합이다.(자료구조)

- 배열을 구성하는 각각의 값을 배열요소라고 하며, 배열에서의 위치를 가리키는 숫자를 인덱스라고 한다.

# 사용 방법

- 배열 선언
  let 변수명;
  

- 배열 초기화
  변수명 = [요소1, 요소2, 요소3 ...];

	let arr;
	arr = [100, 200, 300];
    

- 배열 생성 함수
  let 변수명 = Array(요소1, 요소2, 요소3 ...);
  

- 배열의 접근
  let arr = [100, 200, 300];

	arr[0]  // 100
	arr[1]  // 200
	arr[2]  // 300

 

자바스크립트 배열의 특징

- 배열 요소의 타입이 고정되어 있지 않다.

ex)

    let arr = [1, 1.5, '김사과', true]

 

- 배열 요소의 인덱스가 연속적이지 않아도 된다.

ex)

    let arr;
    arr[0] = 1;
    arr[1] = 100;
    arr[4] = 10;
    // index 2, 3은 undefined

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 1</title>
</head>
<body>
    <h2>배열 1</h2>
    <script>
        const user = [1, "apple", "김사과", 20, "서울 서초구"];
        console.log(user);

        console.log(user[0]);
        console.log(user[1]);
        console.log(user[2]);
        console.log(user[3]);
        console.log(user[4]);
        console.log(user[5]);

        user[4] = "서울 강남구";
        console.log(user[4]);

        console.log(user.length);
        console.log('----------------');

        for(let i=0; i<user.length; i++) {
            console.log(user[i]);
        };
    </script>
</body>
</html>
결과

- 인덱스가 넘어가면 에러가 나지 않고 undefined으로 나온다.

- 인덱스 값을 바꿀 때, 인덱스 값을 새로 주면 된다.

- length를 이용하여 길이를 확인할 수 있다.

 

배열의 속성
  • push() : 배열의 요소를 추가한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const user = [1, "javascript", "자바스크립트", 20, "서울 송파구"];
        
        user.push('자바');		 # push() : 배열의 요소를 추가
        console.log(user);
    </script>
</body>
</html>
결과

 

  • pop() : 배열의 마지막 인덱스 번호에 있는 값을 제거한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const user = [1, "javascript", "자바스크립트", 20, "서울 송파구"];

        let temp = user.pop();		# pop() : 배열의 마지막 인덱스 번호에 있는 값을 제거
        console.log(user);
        console.log(temp);
    </script>
</body>
</html>
결과

 

  • shift() : 배열의 첫 번째 인덱스 번호에 있는 값을 제거한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const user = [1, "javascript", "자바스크립트", 20, "서울 송파구"];

        console.log(user);
        temp = user.shift();		# shift() : 배열의 첫 번째 인덱스 번호에 있는 값을 제거
        console.log(user);
        console.log(temp);

    </script>
</body>
</html>
결과

 

  • concat() : 두 배열의 요소를 합친다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const user = [1, "javascript", "자바스크립트", 20, "서울 송파구"];

        const profile = ["자바", "A형", "istp"]
        result = user.concat(profile);		# concat() : 두 배열의 요소를 합침
        console.log(result);

    </script>
</body>
</html>
결과

 

  • join() : 배열 요소 사이에 원하는 문자를 삽입한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const user = [1, "javascript", "자바스크립트", 20, "서울 송파구"];

        result = user.join('😀');		# join() : 배열 요소 사이에 원하는 문자를 삽입
        console.log(result);
        console.log(typeof(user));
        console.log(typeof(result));
    </script>
</body>
</html>
결과

 

  • sort() : 배열의 요소를 오름차순으로 나열한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const arr = ['a', 'z', 'c', 'f', 'r'];
        
        arr.sort();			# sort() : 배열의 요소를 오름차순
        console.log(arr);
    </script>
</body>
</html>
결과

 

  • reverse() : 배열의 요소를 역순으로 배치한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 2</title>
</head>
<body>
    <h2>배열 2</h2>
    <script>
        const arr = ['a', 'z', 'c', 'f', 'r'];

        arr.reverse(); 		# reverse() : 배열을 역순으로 재배치
        console.log(arr);
    </script>
</body>
</html>
결과

 

배열을 이용한 반복
const arr = [10, 20, 30];
const user = [userid:"javascript", name:"자바스크립트", age:20];
  • for in 문

- 변수에 배열 인덱스 또는 객체의 key가 저장되며 반복한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 3</title>
</head>
<body>
    <h2>배열 3</h2>
    <script>
        const userArray = [1, 'javascript', '자바스크립트', 20, '서울 송파구'];
        const userObj = {userid:'javascript', name:'자바스크립트', age:20};

        # for in 배열
        for(let i in userArray) {
            console.log(`i:${i}, userArr[${i}]: ${userArray[i]}`);
        };


        # for in 객체
        for(let i in userObj) {
            console.log(`i:${i}, userObj[${i}]: ${userObj[i]}`);
        };
    </script>
</body>
</html>
배열 결과
객체 결과

 

  • for of 문

- 변수에 배열 value가 저장되며 반복한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 3</title>
</head>
<body>
    <h2>배열 3</h2>
    <script>
        const userArray = [1, 'javascript', '자바스크립트', 20, '서울 송파구'];
        const userObj = {userid:'javascript', name:'자바스크립트', age:20};

        # for of 배열
        for(let v of userArray) {
            console.log(`v:${v}`);
        };
    </script>
</body>
</html>
결과

 

  • forEach 문

- 배열에서만 사용가능하며 요소의 개수만큼 반복한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 3</title>
</head>
<body>
    <h2>배열 3</h2>
    <script>
        const userArray = [1, 'javascript', '자바스크립트', 20, '서울 송파구'];
        const userObj = {userid:'javascript', name:'자바스크립트', age:20};

        userArray.forEach(function(v, i, arr){
            console.log(`v:${v}, i:${i}, arr:${arr}`);
        });
    </script>
</body>
</html>
결과

 


 

함수
사용자 정의 함수(function)

- 하나의 특별한 목적의 작업을 수행하도록 설계된 독립적인 블록으로, 필요할 때마다 해당 작업을 반복 수행할 수 있다.

- 코드를 재활용하기 위한 목적이 있다.

  • 함수 선언식
# 사용 방법

function 함수명(매개변수1, 매개변수2, ..) {
    함수가 호출되었을 때 실행할 문장;
    ...
    return 값;
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>함수</title>
</head>
<body>
    <h2>함수</h2>
    <script>
        function func1() {
            console.log(`func1() 호출!`);
        }

        func1();
        func1();
    </script>
</body>
</html>
결과

 

  • 함수 표현식
# 사용 방법

const 변수명 = function(매개변수1, 매개변수2, ..) {
    함수가 호출되었을 때 실행할 문장;
    ...
    return 값;
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>함수</title>
</head>
<body>
    <h2>함수</h2>
    <script>
        function func4(){
            return '🍔';
        }

        func4();
        console.log(func4());
        const presents = func4();
        console.log(presents);
    </script>
</body>
</html>
결과

 

  • 디폴트 매개변수

- 매개변수의 값을 설정한다.

- 매개변수의 값을 정하지 않으면 기본값을 변수에 저장한다.

# 사용 방법

function 함수명(매개변수1=값1, 매개변수2=값2, ...) {
    함수가 호출되었을 때 실행할 문장;
    ... 
    return 값;
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>함수</title>
</head>
<body>
    <h2>함수</h2>
    <script>
        function func5(num1=1, num2=1) {
            console.log(`num1의 값: ${num1}, num2의 값: ${num2}`);
            console.log(`${num1} * ${num2} = ${num1 * num2}`);
        }

        func5(10, 3);  
        func5(10);
        func5();
    </script>
</body>
</html>
결과

 

  • 나머지 매개변수

- 생략 접두사(...)를 사용하여 특정 위치의 인수부터 마지막 인수까지 한 번에 지정할 수 있다.

# 사용 방법

function 함수명(매개변수1, ...매개변수2) {
    함수가 호출되었을 때 실행할 문장;
    ...
    return 값;
}

# 들어가는 값 위치
함수명(값1, 값2, 값3, 값4);

매개변수1: 값1
매개변수2: 갑2, 값3, 값4
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>함수</title>
</head>
<body>
    <h2>함수</h2>
    <script>
        function func6(...x) {
            console.log(`x의 값: ${x}`);
            console.log(`x의 타입: ${typeof(x)}`);

            for(i in x){
                console.log(`i의 값: ${i}, x[${i}]: ${x[i]}`);
            }
        }

        func6(30, 50, 80, 100, 40);
        func6(50, 80);
    </script>
</body>
</html>
결과

 

호이스팅

- 인터프리터가 변수와 함수의 메모리 공간을 선언 전에 미리 할당하는 것이다.

- var로 선언한 변수의 경우 호이스팅 시 undefined로 변수를 초기화한다.

- let과 const로 선언한 변수의 경우 호이스팅 시 변수를 초기화하지 않는다.

 

화살표 함수

- function 키워드를 사용하여 함수를 만드는 것보다 간단하게 표현한다.

- 화살표 함수는 항상 익명이고, return은 생략하며, 모든 화살표 함수는 return형이다.

# 사용 방법

const 변수명 = function(){
    ...
}					# 화살표 함수 사용하지 않은 모습

# 매개변수가 없는 경우
const 변수명 = () => {
    ...
}

const 변수명 = () => 문장;


# 매개변수가 있는 경우
const 변수명 = 매개변수1 => {
    ...
}

const 변수명 = (매개변수1, 매개변수2, ..) => {
    ...
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>화살표 함수</title>
</head>
<body>
    <h2>화살표 함수</h2>
    <script>
        const func1 = () => console.log("안녕하세요. 자바스크립트!");
        
        func1();

        console.log('-------------');

        const func2 = x => x * x;
        const result = func2(10);
        console.log(`10의 제곱:${result}`);

        
        const func3 = (x, y) => {
            let sum = 0;
            for(let i=x; i<=y; i++) {
                sum += i;
            }
            return sum;
        }
        const total = func3(1, 100);
        console.log(`1부터 100까지의 합: ${total}`);

        console.log('-------------');

        let age = Number(prompt("나이를 입력하세요"))
        const isAdult = (age > 19) ? () => console.log("성인입니다.") : () => console.log("미성년입니다.");
        isAdult();
    </script>
</body>
</html>
func1 결과
func2 결과

 


 

객체
객체(Object)

- 하나의 주체를 가지고 관련있는 프로퍼티(Property)를 가지고 있는 집합이다.

 

프로퍼티(Property)

- 이름과 값으로 구성된 정렬되지 않은 집합이다.

- 프로퍼티 함수도 저장할 수 있다.(프로퍼티 메서드)

 

객체를 생성하는 방법
  • 리터럴 표기법
# 사용 방법

const 변수명 = {
    프로퍼티명1:값1,
    프로퍼티명2:값2,
    ...
    프로퍼티명n:function(){
        ...
    }
}
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>객체 만들기</title>
</head>
<body>
    <h2>객체 만들기</h2>
    <script>
        // 리터럴 표기법
        const Rucy = {
            name: '루시',
            age: 14,
            color: 'white',
            birthday: '20091210',
            getBirthday: function() {
                return this.birthday;
            }
        }

        console.log(Rucy.name);
        console.log(Rucy.age);
        console.log(Rucy.color);
        console.log(Rucy.birthday);
        console.log(Rucy.getBirthday);
        console.log(Rucy.getBirthday());
    </script>
</body>
</html>
결과

 

  • 생성자를 이용한 표기법

- 객체를 만드는 함수이다. 

- new 연산자를 사용하여 객체를 생성하고 초기화할 수 있다.

- 같은 형태의 객체를 여러개 생성할 때 좋다.

# 사용 방법

function 함수명(매개변수1, 매개변수2 ...) {
    this.프로퍼티1 = 값1;
    this.프로퍼티2 = 값2;
    ...
    this.프로퍼티n = function(){
        ...
    }
}

const 변수1 = new 함수명(값1, 값2, ...);
const 변수2 = new 함수명(값1, 값2, ...);
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>객체 만들기</title>
</head>
<body>
    <h2>객체 만들기</h2>
    <script>
        //생성자를 이용한 객체
        function Dog(name, color) {
            this.name = name;
            this.color = color;
            this.eat = function() {
                return `${this.name} 사료를 먹습니다.`;
            }
        }

        const PPomi = new Dog('뽀미', '흰색');
        console.log(PPomi.name);
        console.log(PPomi.color);
        console.log(PPomi.eat());
    </script>
</body>
</html>
결과

 

  • 클래스를 이용한 표기법

- ECMA Script6에 추가된 객체 생성 방법으로 내부적으로 생성자를 이용한 객체 생성 방법과 동일하게 작동한다.

# 사용 방법

const 클래스명 = class {
    constructor(매개변수1, 매개변수2, ...) {
        this.프로퍼티1 = 값1,
        this.프로퍼티2 = 값2,
        ...
    }

    메소드명(매개변수1, 매개변수2, ...) {
        ...
    }
}

const 변수명1 = new 클래스명(값1, 값2, ...);
const 변수명2 = new 클래스명(값1, 값2, ...);
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>객체 만들기</title>
</head>
<body>
    <h2>객체 만들기</h2>
    <script>
        // 클래스를 이용한 객체 생성
        const Student = class {
            constructor(name, hp, age) {
                this.name = name;
                this.hp = hp;
                this.age = age;
            }
            getName() {
                return `이름은 ${this.name} 입니다.`;
            }
        }

        const apple = new Student('김사과', '010-0000-0000', 20);
        console.log(apple.name);
        console.log(apple.hp);
        console.log(apple.age);
        console.log(apple.getName);
        console.log(apple.getName());

    </script>
</body>
</html>
결과

 

프로토타입(Prototype)

- 모든 객체는 프로토타입이라는 객체를 가지고 있고, 프로토타입으로부터 프로퍼티와 프로퍼티 메서드를 상속받는다.

- 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며, 상속되는 정보를 제공하는 객체를 프로토타입이라고 한다.

# 예시

const animal = new Animal();		# Animal.prototype, Object.prototype
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프로토타입</title>
</head>
<body>
    <h2>프로토타입</h2>
    <script>
        function Dog(color, name, age) {
            this.color = color;
            this.name = name;
            this.age = age;
        }

        const Rucy = new Dog('흰색', '루시', 14);
        console.log(Rucy);
        console.log(`이름: ${Rucy.name}`);
        console.log(`색상: ${Rucy.color}`);
        console.log(`나이: ${Rucy.age}`);
        Rucy.family = '포메라니안';
        Rucy.getFamily = function() {
            return this.family;
        }
        console.log(`종: ${Rucy.family}`);
        console.log(`getfamily: ${Rucy.getFamily()}`);

        const PPomi = new Dog('흰색', '뽀미', 6);
        console.log(`이름: ${PPomi.name}`);
        console.log(`색상: ${PPomi.color}`);
        console.log(`나이: ${PPomi.age}`);
        console.log(`종: ${PPomi.family}`);
        // console.log(`getfamily: ${PPomi.getFamily()}`);


        Dog.prototype.owner = '김사과';
        Dog.prototype.run = function() {
            return this.name + ' 달립니다.';
        }

        console.log(`Rucy 소유자: ${Rucy.owner}`);
        console.log(`PPomi 소유자: ${PPomi.owner}`);

        console.log(`Rucy run(): ${Rucy.run()}`);
        console.log(`PPomi run(): ${PPomi.run()}`);
    </script>
</body>
</html>
결과

 

Math 객체

 

  • min() : 가장 작은 수를 반환한다. 매개변수가 전달되지 않으면 Infinity를 반환한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <script>
        # min() : 가장 작은 수를 반환. 매개변수가 전달되지 않으면 infinity를 반환
        console.log(Math.min());
        console.log(Math.min(1, 10, -10, 1000, 0, '-100'));
        console.log(Math.min(1, 10, -10, '마이너스천', 0, '-100'));
    </script>
</body>
</html>
결과

 

  • max() : 가장 큰 수를 반환한다. 매개변수가 전달되지 않으면 -Infinity를 반환한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <script>
        # max() : 가장 큰 수를 반환. 매개변수가 전달되지 않으면 -Infinity를 반환
        console.log(Math.max());
        console.log(Math.max(1, 10, -10, 1000, 0, '-100'));
        console.log(Math.max(1, 10, -10, '마이너스천', 0, '-100'));
    </script>
</body>
</html>
결과

 

  • round() : 소수점 첫 번째 자리에서 반올림하여 그 결과를 반환한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <script>
        # round() : 소수점 첫 번째 자리에서 반올림하여 그 결과를 반환
        console.log(Math.round(10.49));
        console.log(Math.round(10.5));
        console.log(Math.round(-10.5));
        console.log(Math.round(-10.51));
    </script>
</body>
</html>
결과

 

  • floor() : 소수점을 버림 하여 그 결과를 반환한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <script>
        # floor() : 소수점을 버림
        console.log(Math.floor(10.49));
        console.log(Math.floor(10.5));
        console.log(Math.floor(-10.5));
        console.log(Math.floor(-10.51));
    </script>
</body>
</html>
결과

 

  • ceil() : 소수점 첫 번째 자리에서 소수점을 올림 하여 그 결과를 반환한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <script>
        # ceil() : 소수점 첫 번째 자리에서 소수점을 올림
        console.log(Math.ceil(10.49));
        console.log(Math.ceil(10.5));
        console.log(Math.ceil(-10.5));
        console.log(Math.ceil(-10.51));
    </script>
</body>
</html>
결과

 

  • random() : 0보다 크거나 같고 1보다 작은 무작위 소수를 반환한다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <script>
        # random() : 0보다 크거나 같고 1보다 작은 무작위 소수를 반환
        const ram = Math.random();
        console.log(ram);

        const number = Math.ceil(Math.random() * 10);
        console.log(number);
    </script>
</body>
</html>
결과

 

상속

- 클래스 기반의 객체지향 언어와 다르다. 자바스크립트는 프로토 타입 기반의 객체지향 언어이다.

 


 

문제
가위바위보 게임 만들기
게임 방식   

    가위, 바위, 보 중 하나를 입력하세요. 가위

    컴퓨터: 바위, 유저: 가위 -> 패

    가위, 바위, 보 중 하나를 입력하세요. 바위

    컴퓨터: 가위, 유저: 바위 -> 승
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가위바위보 게임</title>
</head>
<body>
    <h2>가위바위보 게임</h2>
    <script>
        let computer;
        const number = Math.ceil(Math.random() * 10);
        if (number > 6){
            computer = '가위';
        }
        else if(number <= 6){
            computer = '바위';
        }
        else if(number < 3){
            computer = '보'
        }
        for(;;){
            let str = prompt("가위, 바위, 보 중 하나를 입력하세요");
            if (str == computer){
                console.log(`컴퓨터: ${computer}, 유저: ${str}  -> 비겼습니다.`)
            }
            else if((str == '가위' && computer == '바위') || (str == '바위' && computer == '보') || (str == '보' && computer == '가위')){
                console.log(`컴퓨터: ${computer}, 유저: ${str}  -> 유저 패`)
            }
            else{
                console.log(`컴퓨터: ${computer}, 유저: ${str}  -> 유저 승.`)
                break;
            }
        }
        console.log("프로그램을 종료합니다.")
    </script>
</body>
</html>
결과
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가위바위보 게임</title>
</head>
<body>
    <h2>가위바위보 게임</h2>
    <script>
        while(true){
            const com = Math.ceil(Math.random()*3);
            user = prompt("가위바위보 중 하나를 입력하세요");
            
            if(user == '가위'){
                if(com == 1){
                    console.log("컴퓨터: 가위, 유저: 가위 -> 비겼습니다.");
                }else if(com == 2){
                    console.log("컴퓨터: 바위, 유저: 가위 -> 졌습니다.");
                }else if(com == 3){
                    console.log("컴퓨터: 보, 유저: 가위 -> 이겼습니다.");
                    break;
                }
            }else if(user == '바위'){
                if(com == 1){
                    console.log("컴퓨터: 가위, 유저: 바위 -> 이겼습니다.");
                    break;
                }else if(com == 2){
                    console.log("컴퓨터: 바위, 유저: 바위 -> 비겼습니다.");
                }else if(com == 3){
                    console.log("컴퓨터: 보, 유저: 바위 -> 졌습니다.");
                }
            }else if(user == '보'){
                if(com == 1){
                    console.log("컴퓨터: 가위, 유저: 보 -> 졌습니다.");
                }else if(com == 2){
                    console.log("컴퓨터: 바위, 유저: 보 -> 이겼습니다.");
                    break;
                }else if(com == 3){
                    console.log("컴퓨터: 보, 유저: 보 -> 비겼습니다.");
                }
            }
        }
        console.log("프로그램을 종료합니다.")
    </script>
</body>
</html>
결과

 

로또번호 뽑기 프로그램 만들기
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로또번호</title>
</head>
<body>
    <h2>로또번호</h2>
    <script>
        const lotto = [0, 0, 0, 0, 0, 0];
        for(let i=0; i<lotto.length; i++){
            lotto[i] = Math.ceil(Math.random() * 45);
            for(let j=0; j<i; j++){
                if(lotto[i] == lotto[j]){
                    i--;
                }
            }
        }
        lotto.sort(function(p, c){return p-c})
        console.log(lotto);
    </script>
</body>
</html>
결과