변수에 할당 가능, 중괄호{} 사용
let spaceship = {
'Fuel Type': 'diesel',
color: 'silver'
};
<속성에 엑세스하는 방법>
1. 점 표기법 '.' - 개체 이름에 공백 없을 때
let spaceship = {
homePlanet: 'Earth',
color: 'silver'
};
spaceship.homePlanet; // Returns 'Earth',
spaceship.color; // Returns 'silver',
spaceship.favoriteIcecream; // Returns undefined
(해당 객체에 존재하지 않는 속성에 엑세스하면 undefined 반환)
이렇게도
let spaceship = {
homePlanet: 'Earth',
color: 'silver',
'Fuel Type': 'Turbo Fuel',
numCrew: 5,
flightPath: ['Venus', 'Mars', 'Saturn']
};
let crewCount = spaceship.numCrew;
let planetArray = spaceship.flightPath;
2. 대괄호 표기법 '[]' - 개체 이름에 공백 있는 경우('')
let spaceship = {
'Fuel Type': 'Turbo Fuel',
'Active Duty': true,
homePlanet: 'Earth',
numCrew: 5
};
spaceship['Active Duty']; // Returns true
spaceship['Fuel Type']; // Returns 'Turbo Fuel'
spaceship['numCrew']; // Returns 5
spaceship['!!!!!!!!!!!!!!!']; // Returns undefined
let returnAnyProp = (objectName, propName) => objectName[propName];
returnAnyProp(spaceship, 'homePlanet'); // Returns 'Earth'
다른 예
let spaceship = {
'Fuel Type' : 'Turbo Fuel',
'Active Mission' : true,
homePlanet : 'Earth',
numCrew: 5
};
let propName = 'Active Mission';
let isActive = spaceship[propName];
console.log(spaceship[propName]); // Output: true
<속성 할당>
속성이 개체에 이미있는 경우
이전에 보유한 값이 새로 할당 된 값으로 대체된다/
해당 이름의 속성이없는 경우 새 속성이 개체에 추가된다
const spaceship = {type: 'shuttle'};
spaceship = {type: 'alien'}; // TypeError: Assignment to constant variable.
spaceship.type = 'alien'; // Changes the value of the type property
spaceship.speed = 'Mach 5'; // Creates a new key of 'speed' with a value of 'Mach 5'
속성 삭제 가능(delete)
const spaceship = {
'Fuel Type': 'Turbo Fuel',
homePlanet: 'Earth',
mission: 'Explore the universe'
};
delete spaceship.mission; // Removes the mission property
다른 예
let spaceship = {
'Fuel Type' : 'Turbo Fuel',
homePlanet : 'Earth',
color: 'silver',
'Secret Mission' : 'Discover life outside of Earth.'
};
spaceship.color = 'glorious gold'; // color 바꾸기
spaceship.numEngines = 7; // 새 속성 추가
delete spaceship['Secret Mission']; // 지우기
<메소드>
객체에 저장된 데이터가 함수인 경우
const alienShip = {
invade: function () {
console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.')
}
}; 에서 콜론(:)과 function 생략 가능
const alienShip = {
invade () {
console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.')
}
}; 이렇게!
alienShip.invade(); // Prints 'Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.'
다른 예
let retreatMessage ='We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';
let alienShip = {
retreat() {
console.log(retreatMessage)
},
takeOff(){
console.log('Spim... Borp... Glix... Blastoff!')
}
};
alienShip.retreat();
// Output: We no longer wish to conquer your planet. It is full of dogs, which we do not care for.
alienShip.takeOff();
// Output: Spim... Borp... Glix... Blastoff!
<중첩된 개체>
const spaceship = {
telescope: {
yearBuilt: 2018,
model: '91031-XLT',
focalLength: 2032
},
crew: {
captain: {
name: 'Sandra',
degree: 'Computer Engineering',
encourageTeam() { console.log('We got this!') }
}
},
engine: {
model: 'Nimbus2000'
},
nanoelectronics: {
computer: {
terabytes: 100,
monitors: 'HD'
},
'back-up': {
battery: 'Lithium',
terabytes: 50
}
}
};
spaceship.nanoelectronics['back-up'].battery; // Returns 'Lithium'
다르게
let spaceship = {
passengers: [{name: 'Space Dog'}],
telescope: {
yearBuilt: 2018,
model: "91031-XLT",
focalLength: 2032
},
crew: {
captain: {
name: 'Sandra',
degree: 'Computer Engineering',
encourageTeam() { console.log('We got this!') },
'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
},
engine: {
model: "Nimbus2000"
},
nanoelectronics: {
computer: {
terabytes: 100,
monitors: "HD"
},
'back-up': {
battery: "Lithium",
terabytes: 50
}
}
};
let capFave = spaceship.crew.captain['favorite foods'][0];
let firstPassenger = spaceship.passengers[0];
<참조로 전달>
객체는 참조로 전달
즉, 객체에 할당 된 변수를 함수에 인수로 전달할 때 컴퓨터는 매개 변수 이름을 해당 객체를 보유하는 메모리의 공간을 가리키는 것으로 해석. 결과적으로 객체 속성을 변경하는 함수는 실제로 객체를 영구적으로 변경함 (객체가 const변수에 할당 된 경우에도 )
const spaceship = {
homePlanet : 'Earth',
color : 'silver'
};
let paintIt = obj => {
obj.color = 'glorious gold'
};
paintIt(spaceship);
spaceship.color // Returns 'glorious gold'
이런 식으로도 가능
let spaceship = {
homePlanet : 'Earth',
color : 'red'
};
let tryReassignment = obj => {
obj = {
identified : false,
'transport type' : 'flying'
}
console.log(obj) // Prints {'identified': false, 'transport type': 'flying'}
};
tryReassignment(spaceship) // The attempt at reassignment does not work.
spaceship // Still returns {homePlanet : 'Earth', color : 'red'};
spaceship = {
identified : false,
'transport type': 'flying'
}; // Regular reassignment still works.
다른 예
let spaceship = {
'Fuel Type' : 'Turbo Fuel',
homePlanet : 'Earth'
};
let greenEnergy = obj =>
obj['Fuel Type'] = 'avocado oil';
let remotelyDisable = obj => {
obj.disabled = true;
}
greenEnergy(spaceship);
remotelyDisable(spaceship);
console.log(spaceship); // Output:
{ 'Fuel Type': 'avocado oil',
homePlanet: 'Earth',
disabled: true }
<개체를 통한 반복> - for...in
let spaceship = {
crew: {
captain: {
name: 'Lily',
degree: 'Computer Engineering',
cheerTeam() { console.log('You got this!') }
},
'chief officer': {
name: 'Dan',
degree: 'Aerospace Engineering',
agree() { console.log('I agree, captain!') }
},
medic: {
name: 'Clementine',
degree: 'Physics',
announce() { console.log(`Jets on!`) } },
translator: {
name: 'Shauna',
degree: 'Conservation Science',
powerFuel() { console.log('The tank is full!') }
}
}
};
for (let crewMember in spaceship.crew) {
console.log(`${crewMember}:
${spaceship.crew[crewMember].name}`);
} // Output:
captain: Lily
chief officer: Dan
medic: Clementine
translator: Shauna
for (let crewMember in spaceship.crew){
console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`)
}; // Output:
Lily: Computer Engineering
Dan: Aerospace Engineering
Clementine: Physics
Shauna: Conservation Science