js实现字典表
使用对象字面量创建字典
JavaScript 中可以通过对象字面量直接实现字典功能,键值对形式存储数据:
const dictionary = {
"key1": "value1",
"key2": "value2"
};
// 访问
console.log(dictionary["key1"]); // 输出 "value1"
使用 Map 对象实现字典
ES6 引入的 Map 类型更适合字典场景,支持任意类型的键且保留插入顺序:
const map = new Map();
map.set("name", "Alice");
map.set(1, "Number Key");
// 访问
console.log(map.get("name")); // 输出 "Alice"
字典的常见操作
添加/更新元素

dictionary["newKey"] = "newValue"; // 对象字面量
map.set("newKey", "newValue"); // Map
删除元素
delete dictionary["key1"]; // 对象字面量
map.delete("key1"); // Map
检查键是否存在

"key1" in dictionary; // 对象字面量
map.has("key1"); // Map
遍历字典
对象字面量遍历
for (const key in dictionary) {
console.log(key, dictionary[key]);
}
// 或使用 Object.keys()
Object.keys(dictionary).forEach(key => {
console.log(key, dictionary[key]);
});
Map 遍历
map.forEach((value, key) => {
console.log(key, value);
});
// 或使用迭代器
for (const [key, value] of map) {
console.log(key, value);
}
性能与特性对比
- 对象字面量:键自动转换为字符串,无法直接使用对象作为键。
- Map:支持任意类型键,提供
size属性直接获取元素数量,迭代效率更高。
根据需求选择实现方式,简单键值存储可用对象字面量,复杂场景推荐使用 Map。






