16_속성 접근자

charlie_·2021년 6월 18일
0

TIL

목록 보기
16/42

# 오늘 한 일

속성 접근자

:: property에 접근하는 방법

  1. 점 표기법(Dot notation)
let a = {
  test: 1
}
console.log(a.test); // 결과값: 1
  1. 괄호 표기법(Bracket notation)
let a = {
  test: 1
}
console.log(a['test']); // 결과값: 1

점 표기법과 괄호 표기법의 차이점

:: 괄호 표기법에서는 key값으로 사용할 수 있는 것의 범위가 더 넓다.

let test = {
  'a': 1,
  '1b': 2,
  'b1': 3,
  'c-1': 4,
  'd 1': 5
}

key값: a, 1b, b1, c-1, d 1
value값: 1, 2, 3, 4, 5

1) key값은 문자열이어야 한다.
(하지만 부득이하게 key값을 number로 시작하는 경우)
점 표기법은 error가 발생하지만 괄호 표기법은 사용 가능하다.

console.log(test.1b); // error
console.log(test['1b']); // 2

2) key값이 string으로 시작하면 string으로 인식한다.

console.log(test.b1); // 3
console.log(test['b1']); // 3

3) key값에는 기호가 들어갈 수 없다.

console.log(test.c-1); // NaN
console.log(test['c-1']); // 4

4) key값에는 공백이 들어갈 수 없다.

console.log(test.d 1); // error
console.log(test['d 1']); // 5

Computed property

:: 대괄호 사용하면 key값에 함수를 담을 수 있다.

function func1(a, b) {
  return a + b;
}

function func2() {
  return 'Welcome';
}

let obj = {
  [`key${func1(3,4)}`] : `result is ${func1(3,4)}`,
  [func2()] : 'hi'
}

console.log(obj);
// 결과값: {key7: result is 7, Welcome: hi}
const key = 'name';
const value = 'Atta';

const user = {};
user[key] = value;

console.log(user.name); // 결과값: Atta
profile
매일 하루에 딱 한 걸음만

0개의 댓글