동적으로 key의 value값을 가져오려면

Zoey·2020년 12월 15일
// Computed properties
// key should be always string
// 우리가 정확하게 어떤 키가 필요한지 모를 때,
// 즉, Runtime에서 결정될 때 Computed properties를 사용

const zoey = { name: 'zoey', age: 30 };

console.log(zoey.name); // .(dot)으로 접근하거나
console.log(zoey['name']); // computed property로 접근

zoey['hasJob'] = true; // property 추가하고 값 할당 가능

console.log(zoey.hasJob); // true



// 💥💥중요💥💥

function printValue(obj, key) {
  console.log(obj.key); // undefined object에 key라는 property 없는데? 
  console.log(obj[key]);
}

printValue(zoey, 'name'); // undefined 
                          // zoey

printValue(zoey, 'age');  // undefined 
                          // 30

출처: https://www.youtube.com/watch?v=1Lbr29tzAA8

0개의 댓글