๐Ÿ“ŒLanguage/JavaScript

TIL) ๊ฐ์ฒด, object ๊ธฐ๋ณธ ๊ฐœ๋… ์‰ฌ์šด ์„ค๋ช…, ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ

hellohailie 2022. 5. 12. 01:23
๋ฐ˜์‘ํ˜•

 

๊ฐ์ฒด๋ฅผ ๋ฐฐ์šฐ๋Š” ์ด์œ !

 

๊ฐ๊ธฐ ๋‹ค๋ฅธ ๊ฐ’์„ ๊ฐ€์ง€์ง€๋งŒ, ์ž…๋ ฅํ•ด์•ผ ํ•˜๋Š” ๋ฐ์ดํ„ฐ์˜ ์ข…๋ฅ˜๊ฐ€ ๋™์ผํ•œ ๊ฒฝ์šฐ ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์†์‰ฝ๊ฒŒ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

๋ชฉํ‘œ!
๋ฐฐ์—ด๊ณผ ๊ฐ์ฒด์˜ ํŠน์ง•์„ ๊ตฌ๋ถ„ํ•˜๊ณ , ๋ฐฐ์—ด๊ณผ ๊ฐ์ฒด์˜ ํŠน์ง•์— ๋”ฐ๋ผ ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐœ๋ฐœ ์‹œ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉ๋˜๋Š”์ง€ ์ดํ•ดํ•œ๋‹ค.
๊ฐ์ฒด ์†์„ฑ(property)์˜ ์ถ”๊ฐ€, ์กฐํšŒ, ๋ณ€๊ฒฝ, ์‚ญ์ œ๋ฅผ ์ž์œ ์ž์žฌ๋กœ ํ•  ์ˆ˜ ์žˆ๋‹ค.
๊ฐ์ฒด ์†์„ฑ ์กฐํšŒ๋ฒ• ๋‘ ๊ฐ€์ง€, dot notation๊ณผ bracket notation์˜ ์ฐจ์ด๋ฅผ ์ดํ•ดํ•œ๋‹ค.
๋ฐฐ์—ด๊ณผ ๊ฐ์ฒด, ๋ฐ˜๋ณต๋ฌธ์„ ์‘์šฉํ•˜์—ฌ ๋Šฅ์ˆ™ํ•˜๊ฒŒ ๋Œ€๋Ÿ‰์˜ ์ •๋ณด๋ฅผ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋‹ค.

 

๊ฐ์ฒด๋Š” ํ‚ค(key)์™€ ๊ฐ’(value)์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. 

 

let user = {
	firstName: ‘Hailie’,
	lastName: ‘Lee',
	email: ‘0000@gmail.com’,
	city: ‘Gyeonggi’
}

// ํ‚ค(key)๋Š” firstName, lastName, email, city
// ๊ฐ’(value)๋Š” ‘Hailie’, ‘Lee', ‘0000@gmail.com’, ‘Gyeonggi’
// ํ‚ค์™€ ๊ฐ’ ์‚ฌ์ด๋Š” ์ฝœ๋ก : ์œผ๋กœ ๊ตฌ๋ถ„ํ•œ๋‹ค.
// ์ค‘๊ด„ํ˜ธ{curly bracket}๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค. 
// ํ‚ค-๊ฐ’ ์Œ์€ ์‰ผํ‘œ,๋กœ ๊ตฌ๋ถ„ํ•ด์ค€๋‹ค. 

 

 

 

๊ฐ์ฒด์˜ ๊ฐ’์— ์ ‘๊ทผํ•˜๋Š” ๋ฐฉ๋ฒ• / ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

 

๋ฐฉ๋ฒ•1. Dot notation

let user = {
	firstName: ‘Hailie’,
	lastName: ‘Lee',
	email: ‘0000@gmail.com’,
	city: ‘Gyeonggi’
}

user.firstName; // 'Hailie'
user.city; // ‘Gyeonggi’

 

 

 

๋ฐฉ๋ฒ•2. Bracket notation => ๋ฐ˜๋“œ์‹œ ์จ์•ผํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ํ‚ค ๊ฐ’์ด ๋ณ€์ˆ˜์ผ๋•Œ!! 

let user = {
	firstName: ‘Hailie’,
	lastName: ‘Lee',
	email: ‘0000@gmail.com’,
	city: ‘Gyeonggi’
}

user['firstName']; // 'Hailie'
user['city']; // ‘Gyeonggi’

 

โญ๏ธโญ๏ธโญ๏ธ์ค‘์š”ํฌ์ธํŠธโญ๏ธโญ๏ธโญ๏ธ

์ง„์งœ key ๊ฐ’์„ ๊ฐ€์ ธ์˜ฌ๋•Œ

user.firstName

user['firstName']

 

firstName๋ผ๋Š” ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ ธ์˜ฌ๋•Œ 

user[firstName]

 

 

๊ฐ’ ์ถ”๊ฐ€ํ•˜๊ธฐ

 

let user = {
	firstName: ‘Hailie’,
	lastName: ‘Lee',
	email: ‘0000@gmail.com’,
	city: ‘Gyeonggi’
}

user['category'] = 'blog';
user.isStudent = false;
user.color = 'yellow';

 

 

 

๊ฐ’ ์‚ญ์ œํ•˜๊ธฐ delete

 

let user = {
	firstName: ‘Hailie’,
	lastName: ‘Lee',
	email: ‘0000@gmail.com’,
	city: ‘Gyeonggi’
}

delete user.email; // email ํ‚ค-๊ฐ’ ์ง€์šฐ๊ธฐ

// users๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๊ฒŒ ๋œ๋‹ค. 
{firstName: ‘Hailie’,lastName: ‘Lee', city: ‘Gyeonggi’}

 

 

์ฐพ๊ณ  ์‹ถ์€ ํ‚ค๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ in ์—ฐ์‚ฐ์ž

 

let user = {
	firstName: ‘Hailie’,
	lastName: ‘Lee',
	city: ‘Gyeonggi’
}

'city' in user; // true
'email' in user; // false
๋ฐ˜์‘ํ˜•