본문 바로가기
JS/JS-basic

JS - 객체

by 임혁진 2024. 1. 28.

객체는 키 : 값 으로  사용된다.

 

<!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>
        var a = {name : '홍길동', age:20 , arr: [1,2,3], func:function(){
            'a 객체'
     }
    }
        //사용법 2가지
        //console.log( typeof a) 1st
        console.log(a.name)
        console.log(a.age)
        console.log(a.arr)
        console.log(a.arr[1])
        a.func()

        //2nd
        console.log(a['name'])
        console.log(a['age'])
        console.log(a['arr'])
        console.log(a['arr'][1])
        console.log(a['func'])
        
        console.log("-----------------------------------------------------------------------")

        //객체안에 객체
        var exam = {math: 80, eng: 70 , kor: 90};
        var person = {
            name : '이순신',
             exam: exam
            }

        console.log(person);

        //person안에 exam안에 있는 eng값을 참조하는 2가지 방법

        console.log('이순신의 수학점수 : '+ person.exam.math);
        console.log('이순신의 영어점수 : '+ person['exam']['eng'])
        console.log('이순신의 국어점수 : '+ person['exam'].kor)
        
        //배열안의 각체
        var arr = [
            {id: 1 , title : 'hello' , redgate : '2020-11-12'},
            {id: 2 , title : 'hello2' , redgate : '2020-11-13'},
            {id: 3 , title : 'hello3' , redgate : '2020-11-14'},

        ]

        console.log ( arr[0].id)
        console.log ( arr[0]["id"])
        /////////
        //arr을 반복을 돌리고 , 그 안에 값을 전부 출력

        for(var i = 0 ; i < arr.length;i++){
            console.log(arr[i].id)
            console.log(arr[i].title)
            console.log(arr[i].redgate)

            console.log(arr[i])
            
        }
        
    
        for(var s in arr){
            console.log(arr[s]['id'])
            console.log(arr[s]['title']);
            console.log(arr[s]['redgate']);
        }

        console.log("-----------------------------------------------------------------------")
        //2nd 객체 선언방법 - function 을 사용합니다.
        //this 키워드로 변수를 나타내면 , 객체생성시 변수가 됩니다

        function Student(age){
            this.name = '홍길동'
            this.age = age;

            this.getInfo = function(age) {
                return this.age;
            }

            this.setInfo = function(age){
                this.age = age;
            }
        }

    //    var s1 =  new Student()
    //    console.log(s1)

       var s = new Student(20);
       console.log(s.getInfo());
       s.setInfo(30);
       console.log(s.getInfo());


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

'JS > JS-basic' 카테고리의 다른 글

JS - JSON파서  (0) 2024.01.28
JS -클로저 은닉  (0) 2024.01.28
JS - 변수의 유효범위 , 클로저  (1) 2024.01.28
JS-함수,익명함수,즉시실행함수,  (0) 2024.01.28
JS - 반복문 , 객체 담기  (1) 2024.01.28