본문 바로가기
D.evelop/JavaScript

[TIL]Javascript - 객체 접근 Dot Notation, Bracket Notation

by Danne 2021. 8. 22.

자바스크립트에서 객체에 접근하는 2가지 방법

 

Dot Notation (점 표기법)

  • object.property
  • ' . '(점)을 이용해서 접근
/* Dot Notation으로 value에 접근하는 방법 */

객체이름.key
let myArray = {
	name : '강당당',
	age : 30,
	city : ['busan', 'seoul'],
	mycheck : true
}
console.log(myArray.name);     // 강당당
console.log(myArray.age);      // 30
console.log(myArray.city);     // ["busan", "seoul"]
console.log(myArray.mycheck);  // true

 

 

 

Bracket Notation (괄호 표기법)

  • object[property_name]
  • ' [] '(대괄호)을 이용해서 접근
  • 값을 한 번 평가한 뒤에 접근
  • 동적인 접근이 가능함
/* Dot Notation으로 value에 접근하는 방법 */

객체이름['key']
let myArray = {
	name : '당당',
	age : 30,
	city : ['busan', 'seoul'],
	mycheck : true
}
console.log(myArray['name']);     // 당당
console.log(myArray['age']);      // 30
console.log(myArray['city']);     // ["busan", "seoul"]
console.log(myArray['mycheck']);  // true

 

 

✅ Dot Notation와 Bracket Notation 공통적인 특징

  • 변수에 할당 가능
let myColors = {
	first : 'white',
	second : 'blue'
}

// 1. myColors의 객체에 key로 접근
// 2. 해당 객체의 value를 새로운 변수에 할당
let myFirstColor = myColors.first;

console.log(myFirstColor);     // white
let myColors = {
	first : 'white',
	second : 'blue'
}

// 1. myColors의 객체에 key로 접근
// 2. 해당 객체의 value를 새로운 변수에 할당
let myFirstColor = myColors['first'];

console.log(myFirstColor);     // white

 

 

✅ Dot Notation와 Bracket Notation 접근의 차이점

  Dot Notation Bracket Notation
숫자가 포함 O O
숫자로 시작 X O
숫자로만 이루어진 X O
특수 문자로 시작 X O
특수 문자가 포함 X O
특수 문자로만 이루어진 X O
$ 또는 _ 포함, 시작 O O
띄워쓰기 포함 X O
변수 포함 X O
동적인 접근    

 

 

✔️ 숫자가 포함 | 숫자로 시작 | 숫자로만 된 key

let myDays = {
	jan1 : '1월 1일',
	'2fev' : '2월 2일',
	33 : '3월 3일',
}

/* Dot Notation */
console.log(myDays.jan1);     // 1월 1일
console.log(myDays.2fev);     // Uncaught SyntaxError: missing ) after argument list
console.log(myDays.'2fev');   // Uncaught SyntaxError: Unexpected string
console.log(myDays.33);       // Uncaught SyntaxError: missing ) after argument list

/* Bracket Notation */
console.log(myDays['jan1']);   // 1월 1일
console.log(myDays['2fev']);   // 2월 2일
console.log(myDays['33']);     // 3월 3일

 

 

✔️ 특수 문자로 시작 | 특수 문자 포함 | 특수문자로만 된 key

let myName = {
	name : '당당',
	'!name' : '댕댕',
	'nam!e' : '동동',
	'###' : '땅땅'
}

/* Dot Notation */
console.log(myName.name);   // 당당
console.log(myName.!name);  // Uncaught SyntaxError: Unexpected token '!'
console.log(myName.nam!e);  // Uncaught SyntaxError: missing ) after argument list
console.log(myName.###);    // Uncaught SyntaxError: Invalid or unexpected token


/* Bracket Notation */
console.log(myName['name']);    // 당당
console.log(myName['!name']);   // 댕댕
console.log(myName['nam!e']);   // 동동
console.log(myName['###']);     // 땅땅

 

 

✔️ $'와 '_'가 포함된 key

let myName = {
	$name : '댕댕',
	nam$e$ : '당당',
	_name : '동동',
	nam_e_ : '동동'
}

/* Dot Notation */
console.log(myName.$name);      // 댕댕
console.log(myName.nam$e$);     // 당당
console.log(myName._name);      // 동동
console.log(myName.nam_e_);     // 동동

 

 

✔️ 띄워쓰기가 포함된 key

let myfamily = {
	'my father' : '아빠',
	mymother : '엄마',
	' ' : '동생'
}

/* Dot Notation */
console.log(myfamily.my father);      // Uncaught SyntaxError: missing ) after argument list
console.log(myfamily.mymother);       // 엄마

/* Bracket Notation */
console.log(myfamily['my father']);   // 아빠
console.log(myfamily['mymother']);    // 엄마
console.log(myfamily[' ']);           // 동생 (공백만으로도 가능)

 

 

✔️ 변수가 포함된 key

let myArray = {
	city : ['busan', 'seoul']
}

let myCity = 'city'

/* Bracket Notation */
console.log(myArray['city']);   // ['busan', 'seoul']
console.log(myArray[myCity]);   // ['busan', 'seoul']

/* Dot Notation */
console.log(myArray.myCity);    // undefined
let myArray = {
	city : ['busan', 'seoul'],
	myCity : "My city is Paris"       // myCity 키 추가
}

let myCity = 'city'

/* Bracket Notation */
console.log(myArray['city']);   // ['busan', 'seoul']
console.log(myArray[myCity]);   // ['busan', 'seoul']
																// myCity를 변수로 인식함

/* Dot Notation */
console.log(myArray.myCity);    // My city is Paris
																// myCity를 객체 안의 Key라고 인식함

⭐️⭐️중요⭐️⭐️ Bracket Notation은 변수를 활용해 객체에 접근할 수 있다!

 

✔️ Bracket Notation의 동적인 접근

let myArray = {
	name : '당당',
	age : 30,
	city : ['busan', 'seoul'],
	mycheck : true
}

console.log(myArray['na'+'me']); // 당당
console.log(myArray.'na'+'me');  // Uncaught SyntaxError

 

 

 

 

  • 필요에 따라 Dot Notation와 Bracket Notation을 병행하여 사용할 수 있다.
/* 고양이를 찾아라 */

let myArray = {
	name : '강당당',
	'2_pet' : {
			cat : '삐용이',
			dog : '빵이'
	}
}

console.log(myArray.2_pet.cat);          // SyntaxError
console.log(myArray['2_pet'].cat);       // 삐용이
console.log(myArray['2_pet']['cat']);    // 삐용이

 

 

 

Q.당신의 이름을 알고 싶어요

let myArray = {
	name : '강당당',
	positon : 'front-end'
}

A. Bracket Notation 으로 반환하는 함수

function findYourName(obj, YourName) { // 1. 인수값(myArray, 'name')을 매개변수에 할당
    return obj[YourName];              // 2. myArray['name']값을 반환
}
findYourName(myArray, 'name');

A. Dot Notation 으로 반환하는 함수

function findYourName(obj, YourName) { // 1. 인수값(myArray, 'name')을 매개변수에 할당
    return obj.YourName;               // 2. myArray.name 값을 반환
}
findYourName(myArray, name);

 

 

 

 

📚참고 자료

codeburst - "JavaScript Quickie— Dot Notation vs. Bracket Notation"

https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781

MDN Web Docs - JavaScript "Property accessors"

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors

 

 

반응형

댓글