자바스크립트 객체에서 특정 속성에 접근하는 방법은 점 표기법(.)이나 대괄호 표기법([])을 사용합니다.
const person1 = {};
person1['firstname'] = 'Mario';
person1['lastname'] = 'Rossi';
console.log(person1.firstname);// "Mario"
const person2 = {
firstname: 'John',
lastname: 'Doe',
};
console.log(person2['lastname']);// "Doe"
(출처 MDN)
// 객체로 정의된 iconMap
const iconMap = {
home: '🏠',
search: '🔍',
user: '👤'
};
const type = 'home';
const Icon = iconMap[type]; // '🏠'가 할당됨
const Icon = iconMap(type) // 에러 - 절대주의, ()는 함수에만
import {
BanknotesIcon,
ClockIcon,
UserGroupIcon,
InboxIcon,
} from '@heroicons/react/24/outline';
const iconMap = {
collected: BanknotesIcon,
customers: UserGroupIcon,
pending: ClockIcon,
invoices: InboxIcon,
};
export function Card({title, value, type }) {
const Icon = iconMap[type];
return (
<div className="rounded-xl bg-gray-50 p-2 shadow-sm">
<div className="flex p-4">
{Icon ? <Icon className="h-5 w-5 text-gray-700" /> : null}
<h3 className="ml-2 text-sm font-medium">{title}</h3>
</div>
<p
className={`${lusitana.className}
truncate rounded-xl bg-white px-4 py-8 text-center text-2xl`}
>
{value}
</p>
</div>
);
}
iconMap[type]는 type 키에 해당하는 속성의 값을 가져오는 대괄호 표기법을 사용한 예입니다. 이는 동적으로 속성 키를 참조할 수 있어 매우 유용합니다.
배열은 숫자 인덱스에 기반하며 일반적으로 iconMap[0], iconMap[1]처럼 숫자 인덱스로 요소를 접근합니다.
const fruits = ["사과", "바나나"];
console.log(fruits.length); // 2
console.log(fruits[0]); // "사과"
//++++++++++
const arrayEmpty = new Array(2);
console.log(arrayEmpty.length); // 2
console.log(arrayEmpty[0]); // undefined이지만, 사실 빈 슬롯입니다.
console.log(0 in arrayEmpty); // false
console.log(1 in arrayEmpty); // false
//++++++++++
const fruits = new Array("사과", "바나나");
console.log(fruits.length); // 2
console.log(fruits[0]); // "사과"
//++++++++++
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Array(7); // [ , , , , , , ]
Array(1, 2, 3); // [1, 2, 3]
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Array(7); // [ , , , , , , ]
Array(1, 2, 3); // [1, 2, 3]
vite.js 시작 - Templates (0) | 2024.05.15 |
---|---|
addEventListener(), on(), onClick (0) | 2024.05.15 |
반짝이는 효과 - tailwindcss (0) | 2024.05.12 |
replace(), replaceAll() - JavaScript (0) | 2024.05.11 |
세미콜론 " ; " - 자바스크립트 (0) | 2024.05.11 |