JavaScript - 使用变量设置对象键


要使用变量设置对象键,代码如下所示 -

范例

 实时演示

<!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>

输出

在输入属性名称和值并单击“单击此处”按钮后 -

更新于: 12-五月-2020

220 次浏览

开始你的 事业

完成课程获得认证

开始
广告