변수로 객체 키를 설정하는 코드는 다음과 같습니다 -
예시
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; color: red; } </style> </head> <body> <h1>Set object key by variable Example</h1> Enter property name<input class="pName" type="text" /><br /> Enter property value<input class="pName" type="text" /> <br /> <div class="sample"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to set property name and value to above text fields respectively </h3> <script> let sampleEle = document.querySelector(".sample"); let propertyKey = document.querySelector(".pName"); let propertyValue = document.querySelectorAll(".pName")[1]; let testObj = { a: "Hello", }; document.querySelector(".Btn").addEventListener("click", () => { testObj[propertyKey.value] = propertyValue.value; sampleEle.innerHTML ="testObj[" + propertyKey.value + "] = "+testObj[propertyKey.value]; }); </script> </body> </html>
출력
속성 이름과 값을 입력하고 '여기를 클릭' 버튼을 클릭하면 -