Dot Notation & Bracket Notaion

예진·2023년 6월 6일

JavaScript

목록 보기
11/13

객체의 속성, 데이터에 접근하는 방법

  • Dot Notation
  • Bracket Notaion

1. Dot Notation(점 표기법)

let obj = {
    name: 'jin',
    age: '25',
    healthy: true
};

console.log(obj.name);     // jin
console.log(obj.age);      // 25
console.log(obj.healthy);  // true 
  • object.property 의 형태로 사용

  • 정적으로 접근이 확정됨

  • key값이 동적으로 변할 때 사용에 한계가 있음


2. Bracket Notaion

let obj = {
    name: 'jin',
    age: '25',
    healthy: true
};

console.log(obj['name']); // jin
console.log(obj['age']); // 25
console.log(obj['healthy']); // true
  • object.['property'] 의 형태로 사용

  • key 값이 변수일 때 주로 사용

  • 값을 한 번 평가한 뒤에 접근

  • 동적인 접근이 가능함

3. 값 추가하기

let obj = {
    name: 'jin',
    age: '25',
    healthy: true
};

//객체 값 추가

console.log(obj.country = 'korea'); 
// { name: 'jin', age: '25', healthy: true, country: 'korea' }

console.log(obj['job'] = 'engineer'); 
// { name: 'jin', age: '25', healthy: true, country: 'korea', job: 'engineer' }

4. delete 연산자로 객체 값 제거하기

let obj = {
    name: 'jin',
    age: '25',
    healthy: true
};

//객체 값 삭제

console.log(delete obj.country); 
// { name: 'jin', age: '25', healthy: true, job: 'engineer' }

console.log(delete obj['job']);
// { name: 'jin', age: '25', healthy: true }

5. Dot Notation, Bracket Notation 차이

그렇다면 언제 Dot Notation 또는 Bracket Notation을 사용해야하는 걸까?
Dot Notation, Bracket Notation 차이는 다음과 같다.

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

이처럼 Dot Notation은 사용하는데 여러 제한이 있다.

function getValue(obj, key) {
  
  return obj[key];
}

동적으로 접근 할 경우, argument의 property(key)가 문자열로 들어올지, 아니면 특수문자가 섞인 문자열이 불러올지 알 수 없는 경우가 있을 수 있다. 이때 Dot Notation의 사용이 제한되기 때문에, Bracket Notation을 사용해 주어야한다.

profile
Front-End Developer

0개의 댓글