const superman = {
name : 'clark',
age : 33,
}
// 해당 값이 있고
const name = 'clark';
const age = 33;
// 해당 객체가 있음
// 해당 객체의 name에는 name변수가 들어가 있고, age에는 age변수가 들어가 있음
const superman = {
name: name,
age: age,
gender: 'male',
}
// 다음과 같이 생략 가능
const superman = {
name,
age,
gender: 'male',
}
// 존재하지 않는 프로퍼티 호출 시 undefined
superman.birthday;
// undefined
// in 연산자로 프로퍼티 존재 여부 확인
'birthday' in superman;
// false
for (let key in superman) {
console.log(key);
console.log(superman[key]);
}
const superman = {
name : 'clark',
age : 33,
}
// console.log(superman.name);
// console.log(superman['age']);
superman.birthday = '2022-10-31';
superman['hobby'] = 'footbaall';
delete superman.birthday;
console.log(superman);
function makeObject(name, age){
return {
name, // name : name
age, // age : age
hobby : 'football',
}
}
const Mike = makeObject('Mike', '30');
console.log(Mike);
console.log('age' in Mike); // true
console.log('birthday' in Mike); // false
실습
function isAdult(user) {
// (1) if (user.age < 20){
if(!('age' in user) || user.age < 20){
// user에 age가 없거나 or 20살 미만일 경우 false
return false;
}
return true;
}
const Mike = {
name : "Mike",
age : 33,
}
const Jane = {
name : "Jane",
}
console.log(isAdult(Mike)); // true
// (1) console.log(isAdult(Jane)); // true
// user.age가 없을 경우 undefined가 들어가서 if(false)가 되고, 그렇기 때문에 항상 true를 반환함
console.log(isAdult(Jane)); // false
for ... in 문 예제
const Mike = {
name : "Mike",
age : 30,
};
for (x in Mike){
console.log(x);
console.log(Mike[x]);
}
// "name"
// "Mike"
// "age"
// 30