Map
数据结构和数组在不同场景下的使用差异和优势:
动态键类型和数据关联直观
-
数组 :
let arr = [];
arr[0] = '张三'; // 数字索引存储姓名
arr[1] = 25; // 数字索引存储年龄
arr[2] = '男'; // 数字索引存储性别
// 通过索引获取数据
console.log(arr[0]); // 张三
console.log(arr[1]); // 25
-
Map :
let map = new Map();
map.set('name', '张三'); // 字符串键存储姓名
map.set('age', 25); // 字符串键存储年龄
map.set('gender', '男'); // 字符串键存储性别
// 通过键获取数据
console.log(map.get('name')); // 张三
console.log(map.get('age')); // 25
操作便利性
-
数组 :
let arr = [1, 2, 3, 4, 5];
// 查找元素是否存在
let isExist = arr.includes(3); // true
// 删除元素
arr.splice(2, 1); // 删除索引为2的元素
// 更新元素
arr[1] = 10; // 更新索引为1的元素
-
Map :
let map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
map.set('d', 4);
map.set('e', 5);
// 查找元素是否存在
console.log(map.has('c')); // true
// 删除元素
map.delete('c');
// 更新元素
map.set('b', 10);
查找效率高
-
数组 :
let arr = [1, 3, 5, 7, 9];
// 查找值为7的元素的索引
let index = arr.findIndex(item => item === 7); // 3
-
Map :
let map = new Map();
map.set(1, 'a');
map.set(3, 'b');
map.set(5, 'c');
map.set(7, 'd');
map.set(9, 'e');
// 查找键为7的值
console.log(map.get(7)); // d
遍历方式丰富
-
数组 :
let arr = [1, 2, 3, 4, 5];
// 通过索引遍历
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// 使用forEach遍历
arr.forEach((item, index) => {
console.log(index, item);
});
-
Map :
let map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
// 使用for...of遍历键值对
for (let [key, value] of map) {
console.log(key, value);
}
// 使用keys()遍历键
for (let key of map.keys()) {
console.log(key);
}
// 使用values()遍历值
for (let value of map.values()) {
console.log(value);
}
实际应用场景示例
-
存储对象属性和方法 :
class Plugin {
constructor(name) {
this.name = name;
}
execute() {
console.log(`Plugin ${this.name} is executing.`);
}
}
let plugins = new Map();
plugins.set('plugin1', new Plugin('plugin1'));
plugins.set('plugin2', new Plugin('plugin2'));
// 获取并执行插件
let plugin = plugins.get('plugin1');
plugin.execute(); // Plugin plugin1 is executing.
-
缓存场景 :
let cache = new Map();
// 模拟缓存数据
function fetchData(key) {
// 模拟网络请求获取数据
console.log(`Fetching data for ${key} from network...`);
return `Data for ${key}`;
}
function getFromCache(key) {
if (cache.has(key)) {
console.log(`Cache hit for ${key}`);
return cache.get(key);
} else {
let data = fetchData(key);
cache.set(key, data);
return data;
}
}
// 第一次获取数据,缓存中没有,从网络获取并存入缓存
console.log(getFromCache('user1')); // Fetching data for user1 from network... Data for user1
// 第二次获取相同数据,直接从缓存获取
console.log(getFromCache('user1')); // Cache hit for user1 Data for user1
-
多键多值映射关系 :
let tagsMap = new Map();
// 添加标签和对应的文章
tagsMap.set('javascript', ['ES6新特性', 'JavaScript设计模式']);
tagsMap.set('css', ['CSS布局技巧', 'CSS动画效果']);
tagsMap.set('html', ['HTML5新标签', '语义化HTML']);
// 获取某个标签对应的文章
console.log(tagsMap.get('javascript')); // [ 'ES6新特性', 'JavaScript设计模式' ]
// 遍历所有标签和文章
for (let [tag, articles] of tagsMap) {
console.log(`Tag: ${tag}`);
console.log('Articles:', articles.join(', '));
}