본문으로 바로가기
반응형

 

 

 

 

 

 

이번 포스팅에선

 

자바스크립트의 객체(Object)에 대해서 알아보고자 합니다.

 

 

 

 


 

 

● JavaScript 객체(Object) 

 

 

 

한 사람의 정보를 담는 코드를 작성해보자고 합시다.

 

코드는 아래와 같습니다.

const name = "Lee";
const age = 21;
const height = "184.9"

 

 

그렇다면 학교단위에 학생에 대한 정보를

위의 코드처럼 일일이 변수를 생성하지 않고 하는 방법이 없냐..

 

그럴때 객체(Object)가 쓰입니다.

 

 

 

○ 객체 생성

 

Ex) 학생 정보를 담는 객체 생성

 

// 작성법
object변수이름 = {
	변수이름1 = "값1",
    변수이름2 = "값2",
    변수이름3 = "값3"
}

const player = {
    name: "lee",
    age: 21,
    height: 184.9
};

player   ==>   {name: 'lee', age: 21, height: 184.9}

 

 

작성법에 의해서 만들고자 하는 객체를 선언하고,

 

객체를 불러오면 파이썬의 dictionary와 비슷한 형태로 출력됩니다.

 

 

 

 

 

 

○ 객체(값) 접근 및 추가

 

Ex) 학생 정보를 담는 객체 생성

 

// 값에 접근하기
객체이름.변수이름
or
객체이름['변수이름']

const player = {
    name: "lee",
    age: 21,
    height: 184.9
};

player.name   ==> "lee"     player['name'] ==> "lee"
player.age    ==> 21
player.height ==> 184.9

player.weight =-> 80.3

player ==> {name: 'lee', age: 21, height: 184.9, weight: 80.3}

 

 

.(점) 혹은 대괄호를 통해 객체의 해당하는 값을 불러올 수 있습니다.

 

 

 

 

 

 

○ 객체안에 함수 생성

 

Ex) 학생 정보를 담는 객체 생성

 


const player = {
    name: "lee",
    age: 21,
    height: 184.9,
    sayHello2: function (other) {
       console.log("hello! " + other + " nice to meet you!!");
    }
};


player.sayHello2('lee')  
=> "hello! lee nice to meet you!!"

 

 

값을 입력하는 부분에 함수도 입력이 가능합니다.

 

위의 코드처럼 매개변수를 전달 받을 수도 있습니다.

 

 

 

 

 

 

 

 

 

○ 객체속성 삭제 및 변경

 

       ○ 객체속성 변경

       Ex) 학생 정보를 담는 객체 생성

 

const player = {
    name: "lee",
    age: 21,
    height: 184.9,
    sayHello2: function (other) {
       console.log("hello! " + other + " nice to meet you!!");
    }
};

plyaer.name = "kim"

player.name   =>  "kim"

 

 

해당 속성의 값을 변경하고자 하는 값으로 넣어주면 됩니다.

 

 

 

 

 

        ○ 객체속성 변경

       Ex) 학생 정보를 담는 객체 생성

 

// 속성 삭제
delete 객체이름.속성

const player = {
    name: "lee",
    age: 21,
    height: 184.9,
    sayHello2: function (other) {
       console.log("hello! " + other + " nice to meet you!!");
    }
};

delete player.name

player  =>  {age: 21, height: 184.9, sayHello2: ƒ}

 

 

delete 를 통해 객체의 속성 값을 삭제할 수 있습니다.

 

 

 

 

 

 

반응형