Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Keyed Collections trong JavaScript

Keyed collections là các tập hợp dữ liệu được sắp xếp theo key chứ không phải index. Chúng mang tính liên kết (associative). Map và Set objects là keyed collections và có thể lặp theo thứ tự chèn (insertion order).

Dưới đây là mã về keyed collections trong JavaScript:

Ví dụ

<!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;    }    .result {       font-size: 20px;       font-weight: 500;       color: blueviolet;    } </style> </head> <body> <h1>Keyed collections trong JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Nhấn nút trên để tạo và hiển thị đối tượng</h3> <script>    let resEle = document.querySelector(".result");    let BtnEle = document.querySelector(".Btn");    BtnEle.addEventListener("click", () => {       let obj = {          name:'Rohan',          age:22,          occupation:'Student',       };       for(i in obj){          resEle.innerHTML += `key = ${i} : value = ${obj[i]} <br>`;       }    }); </script> </body> </html>

Kết quả

Keyed Collections trong JavaScript

Khi nhấn nút 'CLICK HERE':

Keyed Collections trong JavaScript