객체

치로·2024년 8월 21일

1. 객체 생성 과정

  • 빈 객체의 생성 : 아무런 기능이 없는 상태의 빈 객체 (=prototype)
  • 변수의 추가, 함수의 추가, 배열의 추가

2. 빈 객체의 생성

  • 빈 객체를 만드는 것은 블록괄호{}를 지정하는 것으로 표현
    let people = {};

3. 변수의 추가

  • 객체 안에 추가되어 있는 변수를 멤버 변수 혹인 프로퍼티라고 함
  • 변수를 추가하기 위해서는 객체 이름.변수명 = 값 의 형식을 사용함
  • 선언을 위한 별도의 let, const 키워드는 사용되지 않음
    people.name = "hsj";
    people.gender = "F";
<!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>
    <script>
        // 비어있는 객체 생성
        let people = {};

        // 객체 안에 변수를 포함
        people.name = "hsj";
        people.gender = "F";

        // 프로퍼티(=멤버 변수)의 사용
        document.write("<h1>" + people.name + "님은 " + people.gender + "입니다.</h1>");

        // key의 값으로 name, gender가 순차적으로 할당되기 때문에 people[key]를 통해서 객체의 값을 알아낼 수 있음
        for (key in people) {
            document.write("key : " + key + ", value : " + people[key] + "<br>");
        }
    </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>Document</title>
</head>
<body>
    <script>
        let person = {
            key : "value",
            key1 : "value2",
            key2 : true,
            key3 : undefined,
            key4 : [1, 2],
            key5 : function(){}
        };
    </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>Document</title>
</head>
<body>
    <script>
        let grades = {
            list : {aa : 10, bb : 20, cc : 30},
            show : function(){
                document.write('Hello World');
            }
        }
        document.write(grades['list']);
        document.write("<br>");
        document.write(grades['list']['bb'])
        document.write("<br>");
        document.write(grades.list);
        document.write("<br>");
        document.write(grades.list.cc);
        document.write("<br>");
        document.write(grades['show']);
        document.write("<br>");
        document.write(grades['show']());
        document.write("<br>");
        document.write(grades.show());
    </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>Document</title>
</head>
<body>
    <script>
        let person = {
            name : "hsj",
            age : 23
        };
        person.location = "한국";
        person["gender"] = "여성";

        person.name = "han seo jin";

        person = {
            age : 23
        };
    </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>Document</title>
</head>
<body>
    <script>
        const person = {
            name : "hsj",
            age : 23
        };
        person.location = "한국";
        person["gender"] = "여성";

        person.name = "han seo jin";

        // const는 객체 자체를 수정할 때 오류 발생
        person = {
            age : 23
        };

    </script>
</body>
</html>

4. 메서드 안에서 객테 자원 활용

  • 객체 안에 포함된 메서드에서 다른 메서드를 호출하거나, 프로퍼티를 활용하고자 하는 경우에는 this 키워드를 사용
    this.변수이름 = 값;
    let 변수이름 = this.함수이름(값);
<!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>
    <script>
        let people = {};

        // 객체안에 변수 포함
        people.name = "kjh";
        people.gender = "여";

        // 객체 안에 함수를 포함시키기
        people.sayName = function(){
            // 객체 안에 포함된 함수에서 멤버변수에
            // 접근하기 위해서는 반드시 "this."이라는
            // 특수 예약어를 사용해야 한다.
            document.write("<h1>" + this.name + "</h1>");
        }

        /*
            people 객체 안에 메서드 추가
            1. sayGender        -> gender를 화면에 출력
            2. saySomethig(msg) -> msg를 화면에 출력
            3. getName          -> name를 return
            4. getGender        -> gender를 return
            5. sayInfo()        -> "getName()님은  getGender()
                                    입니다" 라는 내용을 화면에 출력
            6. sayName, sayGender, saySomething, sayInfo를 
            각각 호출
        */
        people.sayGender = function(){
            document.write("<h1>" + this.gender + "</h1>");
        }
        
        people.saySomethig = function(msg){
            document.write("<h1>" + msg + "</h1>");
        }
        
        people.getName = function(){
            return this.name;
        }

        people.getGender = function(){
            return this.gender;
        }

        people.sayInfo = function(){
            document.write("<h1>" + this.getName() 
                + "님은 " + this.getGender() + "입니다.</h1>");
        }

        // 호출
        people.sayName();
        people.sayGender();
        people.saySomethig("Hello Javascript");
        people.sayInfo();
    </script>
</body>
</html>

5. 내장객체

  1. String
<!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>
    <script>
        let url = "https://www.NAVER.com/index.html";
        document.write("<p>문자열 : " + url + "</P>");

        // 문자열의 글자 수 리턴
        let len = url.length;
        document.write("<p>문자열의 길이 : " + len + "</P>");

        // 파라미터로 설정된 위치의 글자를 리턴
        let str = url.charAt(4);
        document.write("<p>글자 위치 : " + str + "</P>");
        
        // 파라미터로 전달된 글자가 처음 나타나는 위치를 리턴
        let position = url.indexOf(":");
        document.write("<p>':'이 처음 나타나는 위치 : " + position + "</P>");

        // 파라미터로 전달된 글자가 마지막으로 나타나는 위치
        let position2 = url.lastIndexOf("/");
        document.write("<p>'/'가 마지막에 나타나는 위치 : " + position2 + "</P>");

        // 잘라내기, 시작과 끝 위치를 파라미터로 설정
        let substring = url.substring(0, 5);
        document.write("<p>문자열 자르기 : " + substring + "</P>");

        // 두 번째 파라미터가 없을 경우 끝까지 자른다
        let substring2 = url.substring(7);
        document.write("<p>문자열 자르기 : " + substring2 + "</P>");

        // 모든 글자를 대문자로 변환
        let up = url.toUpperCase();
        document.write("<p>대문자 변환 : " + up + "</P>");

        // 모든 글자를 소문자로 변환
        let low = url.toLocaleLowerCase();
        document.write("<p>대문자 변환 : " + low + "</P>");
    </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>Document</title>
</head>
<body>
    <script>
        let str = "오늘,날씨,매우,습함";

        // ,를 기준으로 문자열을 잘라내, 배열로 리턴
        let data = str.split(",");

        for (let i=0; i<data.length; i++) {
            document.write("<h1>" + data[i] + "</h1>");
        }
    </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>Document</title>
</head>
<body>
    <script>
        // 배열은 객체처럼 배열 안에 아무 요소나 들어갈 수 있음
        let arr = [1, "문자", true, null, undefined, [], {}, function(){}];
        console.log(arr);
    </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>Document</title>
</head>
<body>
    <script>
        let arr = [1, 2, 3, 4, 5];

        // 배열 원소 추가
        arr.push(6);

        // 어떠한 자료형이 추가되어도 상관없다.
        arr.push({name : "hsj"});
    </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>Document</title>
</head>
<body>
    <script>
        let person = {
            name    : "kjh",
            age     : 20,
            tall    : 167
        };
        let personKey = Object.keys(person);

        for(let i=0; i<personKey.length; i++){
            //console.log(personKey[i]);
            const curKey = personKey[i];
            const curValue = person[curKey];
            console.log(`${curKey} : ${curValue}`);
        }

        let personVal = Object.values(person);
        for( let i=0; i<personVal.length; i++ ){
            console.log(personVal[i]);
        }
    </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>Document</title>
</head>
<body>
    <script>
        let arr = [1, 2, 3, 4];

        //내장 함수 for Each
        arr.forEach(function(elm){
            console.log(elm);
        });

        arr.forEach ((elm) => {console.log(elm);});
    </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>Document</title>
</head>
<body>
    <script>
        const arr = [1, 2, 3, 4];
        console.log(arr);

         /*
            arr배열의 요소 각각에 * 2를 한 값을
            새로운 배열 newArr에 할당 후 console.log로 출력
        */

        const newArr = [];
        arr.forEach(function(elm){
            newArr.push(elm * 2);
        });
        console.log(newArr);
    </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>Document</title>
</head>
<body>
    <script>
        const arr = [1, 2, 3, 4];

        // map : 원본 배열의 모든 요소를 돌면서 연산된 값들만 따로 return해준다
        const newArr = arr.map((elm)=>{
            return elm*2;
        });
        console.log(newArr);
    </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>Document</title>
</head>
<body>
    <script>
        const arr = [1, 2, 3, 4];
        let number = 3;
        // 배열 arr에 number 변수에 담겨있는 값이 존재한다면 true,
        // 그렇지 않으면 false

        arr.forEach((elm)=>{
            if (elm === number) {
                console.log(true);
            } 
        });

        // includes
        console.log(arr.includes(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>Document</title>
</head>
<body>
    <script>
        // indexof : 해당 값이 배열에 있으면 index를 없으면 -1을 return
        const arr = [1, 2, 3, 4];
        let number = "3";
        console.log(arr.indexOf(number)); 

        let number2 = 3;
        console.log(arr.indexOf(number2));
    </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>Document</title>
</head>
<body>
    <script>
        // 배열이 단순 숫자값이 아니라. 객체가 할당된 값을 가진다면 indexof는 사용하기 힘듦
        // 그 때 사용하는 것이 findIndex
        const arr = [
            {color : "red"},
            {color : "black"},
            {color : "blue"},
            {color : "green"},
            {color : "blue"}
        ];
        console.log(arr.findIndex((elm)=> elm.color === "green"));

        // find : 만족하는 요소 자체를 반환함
        const element = arr.find((elm) => {
            return elm.color == "blue";
        });
        console.log(element);

        // filter : color가 blue인 값만 가져오기
        // 특정 조건에 맞는 요소를 배열로 다시 반환
        console.log(arr.filter((elm) => elm.color == "blue"));
    </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>Document</title>
</head>
<body>
    <script>
        const arr = [
            {num : 1, color : "red"},
            {num : 2, color : "black"},
            {num : 3, color : "blue"},
            {num : 4, color : "green"},
            {num : 5, color : "blue"}
        ];

        // slice : 배열 잘라오기
        console.log(arr.slice(0,2));

        // concat : 배열 붙이기
        const arr2 = [
            {num : 6, color : "red"},
            {num : 7, color : "black"}
        ];
        console.log(arr.concat(arr2));

    </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>Document</title>
</head>
<body>
    <script>
        let chars = ["나", "다", "가"];

        // sort : 배열의 정령
        chars.sort();
        console.log(chars);
        // 배열의 반환이 아니라 원본 배열의 순서를 정렬

        let numbers = [0, 1, 3, 2, 10, 30, 20];
        numbers.sort();
        console.log(numbers);
        // 정렬의 결과가 이상하게 나온다
        // 숫자 기준이 아니라 문자 기준으로 정렬하기 때문에 사전식으로 정렬
    </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>Document</title>
</head>
<body>
    <script>
        const arr = ["한서진", "님", "안녕하세요", "또 오셨네요"];
        console.log(arr[0], arr[1], arr[2], arr[3]);

        // join : 각 요소를 이어서 출력
        console.log(arr.join());

        console.log(arr.join(" "));
    </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>Document</title>
</head>
<body>
    <script>
        let s = ['이유덕', '이재영', '권종표', '이재영', '박민호', 
        '강상희','이재영', '김지완', '최승혁', '이성연', '박영서',
        '박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌'];
        
        // 1. function naming1()
        // 김씨와 이씨는 각각 몇명인가요?
        // 결과 : kim: 2, lee : 6
        function naming1(){
            let kim = 0;
            let lee = 0;

            for(let i=0; i<s.length; i++){
                if( s[i][0] === "이" ){
                    lee++;
                }
                if( s[i][0] === "김" ){
                    kim++;
                }                
            }

            return "kim : " + kim + ", lee : " + lee;
        }
        document.write(naming1() + "<br/>");


        // 2. function naming2(param)
        // '이재영'이란 이름이 몇 번 반복되나요?
        // 결과 : 이재영 : 3
        function naming2(param){
            let count = 0;
            for(let i=0; i<s.length; i++){
                if(s[i] === param){
                    count++;
                }   
            }
            return param + " : " + count;
        }
        document.write(naming2("이재영") + "<br/>");


        // 3. function naming3()
        // 중복된 이름을 아에 제거한 리스트 return
        // 결과 : 권종표,강상희,김지완,최승혁,이성연,박영서,송정환,김재성
        function naming3(){
            let uniq = [];
            for(let i=0; i<s.length; i++){
                let uni_count = 0;

                for(let j=0; j<s.length; j++){
                    // i와 j가 같다면 uni_count 증가
                    if( s[i] == s[j] ){
                        uni_count++;
                    }
                }
                if( uni_count < 2 ){
                    uniq.push(s[i]);
                }
            }

            return uniq;
        }
        document.write(naming3() + "<br/>");
        
    </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>Document</title>
</head>
<body>
    <script>
        // 두 수 중에서 최대값
        let max = Math.max(100, 123);
        document.write("<h1>최대값 : " + max + "</h1>");

        // 두 수 중에서 최소값
        let min = Math.min(100, 123);
        document.write("<h1>최소값 : " + min + "</h1>");

        // 원주율
        document.write("<h1>원주율 : " + Math.PI + "</h1>");

        // 소수점 반올림
        let num1 = 3.789;
        document.write("<h1>반올림 : " + Math.round(num1) + "</h1>");

        // 소수점 올림과 내림
        document.write("<h1>소수점 올림 : " + Math.ceil(num1) + "</h1>");
        document.write("<h1>소수점 내림 : " + Math.floor(num1) + "</h1>");

        // 절대값
        let num2 = -123;
        document.write("<h1>절대값 : " + Math.abs(num2) + "</h1>");

        // 난수 발생 : 0.0 에서 1.0 사이의 실수형 난수를 구한다
        document.write("<h1>난수 발생 : " + Math.random() + "</h1>");
    </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>Document</title>
</head>
<body>
    <script>
        // 두 수 사이의 랜덤한 정수를 리턴하는 함수
        function random(n1, n2) {
            return parseInt(Math.random() * (n2 - n1 + 1)) +n1;
        }

        // 함수 결과 확인
        let num = random(0, 9);
        document.write("<h1>0~9 사이의 랜덤 숫자 : " + num + "</h1>")
    </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>Document</title>
</head>
<body>
    <script>
        // 1. 5자리 인증번호 생성 후 출력
        // 결과 : 인증번호 - 79483
        function random(n1, n2) {
            return parseInt(Math.random() * (n2 - n1 + 1)) +n1;
        }
        let auth ="";
        for(let i=0; i<5; i++) {
            auth += random(0, 9);
        }
        document.write("<h1>인증번호 : " + auth + "</h1>");

        // 2. 가위. 바위, 보 게임에서 랜덤으로 출력
        let arr = ["가위", "바위", "보"];
        function getGame() {
            // document.write(Math.random() * 3);
            let i = Math.floor(Math.random() * 3);
            document.write("<h1>" + arr[i] + "</h1>");
        }
        getGame();
    </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>Document</title>
</head>
<body>
    <script>
        // 객체 생성
        let mydate = new Date();

        // 년, 월, 일
        let yy = mydate.getFullYear();
        // 월은 0이 1월, 11이 12월을 의
        let mm = mydate.getMonth()+1;
        let dd = mydate.getDate();

        let result = yy + "-" + mm + "-" + dd;
        document.write("<h1>" + result + "</h1>");

        // 요일 출력
        // 일(0) ~ 토(6)
        let days = ["일", "월", "화", "수", "목", "금", "토"];

        //요일
        let i = mydate.getDay();
        let day = days[i];

        // 시, 분, 초
        let hh = mydate.getHours();
        let mi = mydate.getMinutes();
        let ss = mydate.getSeconds();

        let result2 = yy + "-" + mm + "-" + dd + " " + day + "요일" + hh + ":" + mi + ":" + ss;
        document.write("<h1>" + result2 + "</h1>");
    </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>Document</title>
</head>
<body>
    <script>
        // 임의의 날짜, 시간 저장시키기
        let mydate = new Date();
        let days = ["일", "월", "화", "수", "목", "금", "토"];

        mydate.setYear(2024);
        mydate.setMonth(11); // 12월
        mydate.setDate(26);
        mydate.setHours(12);
        mydate.setMinutes(50);
        mydate.setSeconds(55);

        // 년, 월, 일, 시, 분, 초를 리턴 받기
        let yy = mydate.getFullYear();
        let mm = mydate.getMonth()+1;
        let dd = mydate.getDate();
        let i = mydate.getDay();
        let day = days[i];

        let hh = mydate.getHours();
        let mi = mydate.getMinutes();
        let ss = mydate.getSeconds();

        let result1 = yy + "-" + mm + "-" + dd + " " + day + "요일" + hh + ":" + mi + ":" + ss;
        document.write("<h1>" + result1 + "</h1>");
    </script>
</body>
</html>

0개의 댓글