📖 객체(object)란?
여러종류의 데이터를 묶음으로 관리하는 정렬되지 않은 집합이다.
{name(key): ‘김코드'(value), isDeveloper(key): true(value)}
객체의 경우 자바스크립트 내부에서 오브젝트를 저장할 때 프로퍼티의 순서까지 저장되진 않아서 순서대로 출력되지 않는다.
이는 배열과 다른 특징으로, 객체에는 index가 없다고 볼수 있다. (즉, 순서가 없음)
//빈 객체를 생성한다.
let myObj = new Object();
//생성된 객체에 프로퍼티를 할당한다.
myObj.name = '김코드'
myObj.location = 'south korea'
myObj.sayHello = function(){
console.log('Hello' + this.name);
}
console.log(myObj);
//객체이름
let myself = {
name: 'code kim',
// 객체 내부에 중첩된 객체
location: {
country: 'south korea',
city: 'seoul'},
age: 30,
// 배열이 값으로도 들어갈 수 있음
cats: ['냥순', '냥돌']
}
//참고: 오브젝트안에 있는 키의 벨류 = 오브젝트
function person(name, age){
this.name = name;
this.age = age;
this.sayHello = function(){
console.log('Hello'+ this.name);
}
};
let person1 = new Person('a', 20);
let person2 = new Person('b', 30);
let person3 = new Person('c', 28);
객체의 저장된 데이터에 접근하는 방법으로는 key를 이용해서 접근할 수 있다.
키를 이용해 접근하는 방법은 아래와 같이 2가지 방법이 있다.
.을 이용해 접근한다.
-> 객체이름.키네임
입력
위와 같이 입력 시 키에 접근 후 벨류를 출력한다.
객체이름[’키네임’]
✔️ 키에 접근하는 방법으로 변수에도 할당이 가능하다.
→ let 변수이름 = 객체이름[’키네임’]
Dot
Bracket
❌ 객체 사용 시 주의점
- 객체에 key로 접근 시, 자바스트립트 키는 기본적으로 스트링으로 되어있는데 Bracket으로 객체의 키(스트링타입)를 변수에 담아 사용할 수 있다.
- 그러나 Dot notation으로는 위처럼 변수 사용이 불가하기 때문에 이 점을 주의하자! (Dot은 키가 값으로 왔을 때 변수라고 생각하지 않고 키라고 생각함)
//💚변수를 사용한 객체 속성 접근
function objectVariables() {
let testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
let playerNumber = 16; //여기
let player = testObj[playerNumber]; //여기
return player;
}
console.log(objectVariables())
===
//💚객체 속성 추가
function addProperty() {
let myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["Wecode Bootcamp"]
};
myDog.bark = 'woof'; //여기
return myDog;
}
console.log(addProperty())
===
//💚객체 속성 삭제
function deleteProperty() {
let myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["Wecode Bootcamp"],
"bark": "woof"
};
delete myDog.tails; //여기
return myDog;
}
console.log(deleteProperty())
===
//💚객체 안에 객체 접근
function accessObject() {
let myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
//여기
let gloveBoxContents = myStorage.car.inside['glove box']
return gloveBoxContents;
}
console.log(accessObject())
===
//💚객체 안에 배열 속 접근
function accessArray() {
let myPlants = [{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
let foundValue = myPlants[1].list[1] //여기
return foundValue;
}
console.log(accessArray())