객체

hzn·2022년 9월 5일
0

JavaScript

목록 보기
3/17
post-thumbnail

객체

  • 쌍으로 이루어져 있다. (key-value pair)

객체의 값을 사용하는 방법

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'
 user[`email`]; // 'steve@codestates.com'
  • 만약 속성을 문자열로 묶어주지 않을 경우

속성(firstName)을 정의되지 않은 변수로 취급해 Uncaught ReferenceError : 변수가 정의되지 않음 에러가 뜬다.

  • 속성이 동적일 때(key가 변할 때)는 반드시 Bracket notation을 쓴다.

  let person = {
  	name: 'Steve',
    age: 16
   };

  function getProperty(obj, propertyName) {
  	return obj[propertyName]; // propertyName이 string으로 들어오므로.

 // 요구사항
 let output = getProperty(person, 'name');
 console.log(output); // 'Steve'
  let output = getProperty(person, 'age');
 console.log(output); // 16

객체의 값 추가, 삭제, 확인

값 추가하기: Dot notation, Bracket notation

let tweet = {
 	writer : 'stevelee',
    content: '재밌다!'
};
tweet.isPublic = true; // isPublic 키-값 쌍을 추가

// tweet은 다음과 같게 됨
// {writer : 'stevelee', content: '재밌다!', isPublic = true};

값 삭제하기: delete 키워드

let tweet = {
 	writer : 'stevelee',
    createdAt : '2022-09-05 12:04:22'.
    content: '재밌다!'
};
delete tweet.createdAt; // createdAt 키-값 쌍을 지움

// tweet은 다음과 같게 됨
// {writer : 'stevelee', content: '재밌다!'};

키, 값 있는지 확인하기 : in 연산자

let tweet = {
 	writer : 'stevelee',
    createdAt : '2022-09-05 12:04:22'.
    content: '재밌다!'
};

'content' in tweet; // true
'updatedAt' in tweet; // false

0개의 댓글