目录
一、字典
1.概念
字典是一种以键值对形式存储数据的集合。在字典中,每个键都是唯一的,值可以是任意类型。这种结构使得查找、插入和删除操作变得非常高效。
2.特点
- 唯一性:字典中的每个键都是唯一的,不能重复。
- 快速查找:通过键可以快速访问到对应的值,平均时间复杂度为 �(1)O(1)。
- 灵活性:可以存储多种数据类型的值。
3.在JS中如何实现
在 JavaScript 中,可以使用对象({}
)或 ES6 引入的 Map
来实现字典。
4.字典用法
使用对象作为字典
// 创建一个字典
const dictionary = {
"apple": "A fruit that is red or green.",
"banana": "A long yellow fruit.",
"orange": "A citrus fruit."
};
// 查找值
console.log(dictionary["apple"]); // 输出: A fruit that is red or green.
// 添加新键值对
dictionary["grape"] = "A small, round fruit.";
console.log(dictionary["grape"]); // 输出: A small, round fruit.
// 删除键值对
delete dictionary["banana"];
console.log(dictionary["banana"]); // 输出: undefined
使用map
// 创建一个字典
const map = new Map();
map.set("apple", "A fruit that is red or green.");
map.set("banana", "A long yellow fruit.");
// 查找值
console.log(map.get("banana")); // 输出: A long yellow fruit.
// 添加新键值对
map.set("grape", "A small, round fruit.");
console.log(map.get("grape")); // 输出: A small, round fruit.
// 删除键值对
map.delete("apple");
console.log(map.get("apple")); // 输出: undefined
5.应用场景
- 数据存储:可以用来存储用户信息、配置选项、字典数据等。
- 频率统计:统计单词出现频率,例如在文本分析中。
- 快速查找