2021년 3월 9일 화요일
객체란 무엇인가?
객체는 키와 값의 쌍으로 이루어진 집합이다. 중괄호(curly bracket)으로 묶는다.
let person = {
name: 'James', //name은 key, 'James'는 value(값)이다. name: 'James'를 property라고 한다.
age: 20
};
property는 객체의 상태를 나타내는 값이다. property의 구분은 쉼표(,)이다.
key는 value에 접근할 수 있는 식별자 역할을 한다.
이미 존재하는 키를 중복 선언하면 나중에 선언한 property가 먼저 선언된 property를 덮어준다.
let foo = {
name: 'Steve',
name: 'James'
};
console.log(foo); // { name: 'James' }
객체의 값에 접근하는 방법
person.name; // 'James' -> dot notation(마침표 표기법)
person['name']; -> bracket notation(대괄호 표기법): 변수가 동적일 경우 사용
객체 property를 추가할 수 있다.
let person = {
name: 'James',
age: 20
};
person.birthday = '1980-01-01';
person['city'] = 'Seoul';
console.table(person)
name "James" city "Seoul" birth "2010-01-01" age 20
delete 연산자를 사용해 객체 property를 삭제할 수 있다.
delete person.age;
person; // {name: "James", birth: "2010-01-01", city: "Seoul"}
property 존재 확인: in 연산자
key in obj
//key: 키 나타내는 문자열
//obj: 객체명
let person = {
name: 'James',
age: 20
};
console.log('name' in person); //true
console.log('birthday' in person); //false
property 반복 열거: for ... in 문
for( 변수선언문 in 객체) {...}
let person = {
name: 'James',
age: 20,
city: 'Seoul'
};
for(let key in person) {
console.log(key + ':' + person[key]);
}
// name:James
// age:20
// city:Seoul
배열인 경우는 for ... in문 보다는 일반적 for 문, for ... of 문, forEach메서드를 사용하는 것이 좋다.
Object.keys : 객체 자신이 열거 가능한 property 키를 배열로 반환한다.
Object.keys(obj)
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1)); // ["a", "b", "c"]
Object.keys(object1).length; //3 -> Object.keys(obj).length를 하면 객체의 수를 구할 수 있다.
Object.values: 객체 자신이 열거 가능한 property 값(value)을 배열로 반환한다.
let person = {
name: 'James',
age: 20,
city: 'Seoul'
};
Object.values(person); //["James", 20, "Seoul"]
Object.entries: 객체 자신이 열거 가능한 property 키와 값의 쌍의 배열을 배열로 담아 반환한다.
let person = {
name: 'James',
age: 20,
city: 'Seoul'
};
Object.entries(person);
//["name", "James"]
//["age", 20]
//["city", "Seoul"]
//length: 3
Object.entries(person).length; // 3: 객체의 수를 구할 수 있다.
댓글