
객체 = {객체1:{}, 객체2:{}, 객체3:{}}
위와 같이 여러 정보를 담기 위해 "상위-하위 객체" 구조를 생성한 경우
두가지 방식으로 하위객체 및 그 안의 속성을 선택할 수 있다.
[예제 코드]
let currencyRatio = {
USD:{
KRW: 1309.02,
USD: 1,
VND: 24535.00,
unit: "달러"
},
KRW:{
KRW: 1,
USD: 0.00076,
VND: 18.74,
unit: "원"
},
VND:{
KRW: 0.053,
USD: 0.000041,
VND: 1,
unit: "동"
}
};
환율을 나타내는 객체 currencyRatio안에 국가별 화폐단위를 나타내는 객체를 생성한 코드이다.
해당 객체는 4가지의 공통 속성을 가지고 있다.
console.log(currencyRatio.USD.unit)
이 방식은 객체와 속성을 직접 선택하므로 이벤트에 따라 속성과 객체를 변경해서 선택할 수 없으며 값을 고정적으로 사용한다.
console.log(currencyRatio['VND']['unit']);
이 방식도 위와 선택은 동일하나 대괄호[] 안에 속성을 지정한 변수를 담을 경우 이벤트에 따라 선택을 변경할 수 있어 값을 유동적으로 사용할 수 있다.
[예제코드]
let amount = document.getElementById("fromInput").value;
let convertedAmount = amount * currencyRatio[fromCurrency][toCurrency];
객체를 담은 변수 fromCurrency, 속성값을 담은 변수 toCurrency를 대괄호에 삽입함으로써 이벤트 발생시 값이 변동되고 이에따라 환율값(convertedAmount)도 변경된다.
document.querySelectorAll("#from-currency-list a").forEach(menu=>
menu.addEventListener("click",function(){
document.getElementById("fromBtn").textContent = this.textContent;
})
);
1) from-currency-list의 하위 요소(a태그)를 모두 선택하기 위해 querySelectorAll 메서드를 사용
2) addEventListner를 이용해 모든 요소에 "click"이벤트를 적용시킨다.
3) function()안에 click시 실행시킬 코드를 작성
<input type="number" id="fromInput" onkeyup="convert()">
태그 안에 onkeyup이벤트를 직접 적용시키며 해당 이벤트 발생시 convert()메서드 실행
-- onkeyup : 사용자가 누른 키보드의 키가 올라올 때 실행하는 이벤트
function convert(){
let amount = document.getElementById("fromInput").value;
let convertedAmount = amount * currencyRatio[fromCurrency][toCurrency];
document.getElementById("toInput").value = convertedAmount;
}
convert()메서드는 Js에서 작성하며, function convert(){}안에는 이벤트 발생시 실행시킬 코드를 작성한다.