ใน JavaScript ไม่มี Associative Arrays จริงๆ แต่ใช้ Object แทน โดย Key เป็น String ที่ผู้ใช้กำหนด เอง แทน Index ตัวเลข
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Associative Array</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Associative array in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to create associative array and display </h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
let arr = { Name: "Rohan", Class: 9, Age: 16 };
for (let i in arr) {
resEle.innerHTML += "Key = " + i + " : Value = " + arr[i] + "<br>";
}
});
</script>
</body>
</html>
คำอธิบาย
- สร้างด้วย Object Literal:
{ key: value } - เข้าถึง:
obj.keyหรือobj['key'] - ไม่มี Property
.lengthและไม่สามารถใช้for...ofหรือforEachได้โดยตรง - วนลูปด้วย
for...inหรือObject.keys()/values()/entries()
ผลลัพธ์
แสดง Key-Value คู่: "Key = Name : Value = Rohan", "Key = Class : Value = 9", "Key = Age : Value = 16"