자바스크립트(JS) 객체

raincastle1211·2023년 1월 15일

객체란?

객체는 키(key)와 값(value)으로 구성된 프로퍼티(Property)의 집합입니다.
프로퍼티란 객체 안에 선언된 이름과 값으로 이루어진 한 쌍을 의미합니다.
프로퍼티는 "key(키)" : "value(값)" 의 형식으로 객체 안의 콤마(쉼표 ,)로 구분됩니다.

function practiceEnjoy() {
 const testObj = {
   hat: "ballcap",
   shirt: "jersey",
   shoes: "cleats",
};
  
 const hatValue = testObj.hat;
 const shirtValue = testObj.shirt;
  
 return hatValue + ' ' + shirtValue;
}

console.log(practiceEnjoy())

위의 예시에서 testObj는 객체이고 hat은 키(key), "ballcap"은 프로퍼티의 값(value)입니다.
마침표 연산자(.)를 사용하여 객체의 property 값에 접근했습니다.
대괄호를 사용해 객체의 property 값에 접근도 가능합니다.
변수 hatValue의 값으로 "hat" property의 value값을 할당했습니다.
변수 shirtValue의 값으로 "shirt" property의 value값을 할당했습니다.
ballcap jersey가 출력됩니다.

Dot Notation 과 Bracket Notation

두 방법 모두 객체의 프로퍼티에 접근할 수 있습니다.
Dot Notation : 단순 키값 접근
Bracket Notation : 띄어쓰기, -있을때, 변수로 되어있을때

객체 연습해보기

const test = { name: '홍길동', age: 20, city: 'suwon' };
console.log(test.city);
  • 변수 test의 city의 값이므로 suwon이 나옵니다.
const obj = { name: { aa: [0,1] } };
console.log(obj);
  • obj의 객체가 나오므로 { name: { aa: [0, 1] } } 이 나옵니다.
const obj = { name: { aa: [0, 1] } };
console.log(obj.name);
  • 변수 obj의 객체 name의 객체이므로 { aa: [0, 1] } 이 나옵니다.
const obj = { name: { aa: [0, 1] } };
console.log(obj.name.aa[1]);
  • 변수 obj의 객체 name 객체의 aa 객체의 첫 번째 배열이니 1이 나옵니다.
profile
즐거운하루

0개의 댓글