728x90
자바스크립트의 객체는 게임 캐릭터에 비유할 수 있다.
사용자들의 캐릭터는 동일하게 직업과 능력을 가지고 있지만 세부적인 내용은 다르다. 누군가는 김코딩이라는 ID와 마법사라는 직업을 갖고 있지만 다른 누군가는 박해커라는 ID와 전사라는 직업을 가지고 있다. 이렇게 각기 다른 값을 가질 수 있지만 입력해야하는 데이터의 종류가 동일한 경우 객체를 사용하면 손쉽게 데이터를 관리할 수 있다.
객체를 사용하는 방법은 두 가지가 있다. Dot notation 과 Bracket notation 이다.
방법 1 : Dot notation
let user = {
firstName: 'Steve' ,
lastName: 'Lee' ,
email: 'steve@codestates.com' ,
city: 'Seoul'
};
user.firstName; // 'Steve'
user.city; // 'Seoul'
방법 2 : Bracket notation
let user = {
firstName: 'Steve' ,
lastName: 'Lee' ,
email: 'steve@codestates.com' ,
city: 'Seoul'
};
user['firstName']; // 'Steve'
user['city']; // 'Seoul'
연습
stevelee라는 아이디를 가진 유저가 SNS에 새로운 글을 올렸다. 그가 작성한 글 '프리코스 재밌어요!' 라는 내용을 bracket notation으로 어떻게 가져올 수 있을까?
let tweet = {
writer : 'stevelee'
createdAt : '2019-09-10 12-03:33',
content : '프리코스 재밌어요!'
}
정답
tweet.content
// '프리코스 재밌어요!'
tweet["content"]
// '프리코스 재밌어요!'
tweet['content']
// '프리코스 재밌어요!'
tweet[content]
// error
[코드] Bracket notation 할 때 주의점 하나, 따옴표를 안쓰면 변수 취급된다. 마지막 줄의 경우
content is not difined 라는 에러가 뜨는데 이는 변수가 정의되지 않았다는 뜻이다.
tweet['content'] === tweet.content
// true
tweet[content] === tweet.content
// false
tweet[content] === tweet['content']
// false
content 라는 변수를 선언할 경우
let content = 'writer'
tweet[content] === tweet['content']
// false
tweet[content] === tweet['writer']
// true
정리
let tweet = {
writer: 'stevelee',
createdAt: '2019-09-10 12:03:33',
content: '프리코스 재밌어요!'
};
tweet['content'] === tweets.content; // true
dot/bracket notation을 이용해 값을 추가할 수도 있다.
let tweet = {
writer: 'stevelee' ,
createdAt: '2019-09-10 12:03:33' ,
content: '프리코스 재밌어요!'
};
tweet['category'] = '잡담';
tweet.isPublic = true;
tweet.tags = ['#코드스테이츠', '#프리코스'];
delete 키워드를 이용해 삭제가 가능하다.
let tweet = {
writer: 'stevelee' ,
createdAt: '2019-09-10 12:03:33' ,
content: '프리코스 재밌어요!'
};
delete tweets.createdAt; // 키-값 쌍을 지운다.
// tweet은 다음과 같게 된다.
// { writer: 'stevelee', content: '프리코스 재밌어요!' }
in 연산자를 이용해 하당하는 키가 있는지 확인할 수 있다.
let tweet = {
writer: 'stevelee' ,
createdAt: '2019-09-10 12:03:33' ,
content: '프리코스 재밌어요!'
};
'content' in tweet; // true
'updatedAt' in tweet; // false
반응형
'My Wiki (CodesStates) > JS,Node' 카테고리의 다른 글
(3-1) JS/Node 스코프,클로저 - 원시자료형과 참조자료형 (0) | 2021.08.04 |
---|---|
(2-5) JS/Node 배열, 객체 - 객체의 반복 (0) | 2021.08.01 |
(2-3) JS/Node 배열, 객체 - 배열 요소 포함 여부 확인하기 (0) | 2021.08.01 |
(2-2) JS/Node 배열, 객체 - 배열의 반복 (0) | 2021.08.01 |
(2-1) JS/Node 배열, 객체 - 배열 기초, 기초 메소드 (0) | 2021.07.31 |
댓글