如何在 JavaScript 中為物件設定動態屬性鍵?
在下面的示例中,我們將學習如何在 JavaScript 中為物件設定動態屬性鍵。
要向 JavaScript 中的物件新增動態屬性鍵,有三種可能的方法。有三種可能的方法可以為物件設定動態屬性鍵。第一種可能的方法是建立一個鍵並將其分配給物件,第二種可能的方法是使用 define property 方法為物件設定動態屬性鍵,第三種可能的方法是使用 ES6 方法為物件設定動態屬性鍵。我們用合適的例子討論了每種方法。
示例 1
以下程式是建立鍵並將其分配給物件的示例。
<!DOCTYPE html>
<html>
<head>
<title>To set dynamic property keys to an object in JavaScript</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="text-align : center">
<h3>To set dynamic property keys to an object in JavaScript</h3>
<p id="dynamic-keys"></p>
<script>
let Employee = { name : 'Vinay',
emp_id : 101
};
let key = "Company";
Employee[key] = 'Tutorials Point';
document.getElementById("dynamic-keys").innerHTML = 'Employee["name"] : '+ Employee['name'] +'<br/>'+'Employee["emp_id"] : '+Employee['emp_id']+'<br/>'+"Employee[key] : "+Employee[key];
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
示例 2
以下是一個使用 define property 方法為物件設定動態屬性鍵的示例程式。
<!DOCTYPE html>
<html>
<head>
<title>To set dynamic property keys to an object in JavaScript</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="text-align : center">
<h3>To set dynamic property keys to an object in JavaScript</h3>
<p id="dynamic-keys"></p>
<script>
let Employee = { name : 'Vinay',
emp_id : 101
};
let key = "Company";
Employee[key] = 'Tutorials Point';
let key2 = 'role';
Object.defineProperty(Employee, key2,{value: 'Software Engineer'})
document.getElementById("dynamic-keys").innerHTML = 'Employee["name"] : '+ Employee['name'] +'<br/>'+'Employee["emp_id"] : '+Employee['emp_id']+'<br/>'+"Employee[key] : "+Employee[key]+'<br/>'+"Employee[key2] : "+Employee[key2];
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
示例 3
以下是一個使用 ES6 方法為物件設定動態屬性鍵的示例程式。
<!DOCTYPE html>
<html>
<head>
<title>To set dynamic property keys to an object in JavaScript</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<ody style="text-align : center">
<h3>To set dynamic property keys to an object in JavaScript using ES6 Method.</h3>
<p id="dynamic-keys"></p>
<script>
let key1 = "Company";
let key2 = 'role';
let Employee = { name : 'Vinay',
emp_id : 101,
[key1] : 'Tutorials Point',
[key2] : 'Software Engineer'
};
document.getElementById("dynamic-keys").innerHTML = 'Employee["name"] : '+ Employee['name'] +'<br/>'+'Employee["emp_id"] : '+Employee['emp_id']+'<br/>'+"Employee[key1] : "+Employee[key1]+'<br/>'+"Employee[key2] : "+Employee[key2];
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP