字典
1. 定义
除了集合,ES6中同样引入了新的数据结构,那就是字典(Map); 字典最重要额特点就是一一对应的关系,即key: value
字典中的keys是无序的,不可重复的,但是value却可以重复.
相比于数组,字典的下标更加具有语义化,再js中,字典被翻译成Map,表示映射的意思.
2. 字典和js
字典一般使用哈希表实现,但是由于js这门语言的特殊性,在js中Object本身就是一种字典,所以完全可以使用Object来代替字典. 至于后面引入的Map,则可以看成是专门用来实现字典的特殊Object,它比直接使用Object当作字典更加强大!
3. 字典上常见的操作
1. set(key, value): 向字典中添加新的元素
2. remove(key): 通过键来移除对应的数据值
3. has(key): 判断某个key是否在字典中
4. get(key): 通过key获取字典中对应的值
5. clear(): 清空字典
6. size(): 返回字典的大小
7. keys(): 返回字典的key组成的数组
8. values(): 返回字典的values组成的数组
4. 实现字典上的操作
class _Map {
items: Record<PropertyKey, any> = {};
// 在字典中新增一对映射关系
set(key: string, value: any): boolean {
if(this.items.hasOwnProperty(key)){
return false;
}
this.items[key] = value;
return true;
}
// 根据key来移除字典中的某个映射
remove(key: PropertyKey): PropertyKey | null{
if(this.items.hasOwnProperty(key)){
return null;
}
delete this.items[key];
return key;
}
// 判断某个key是否在字典上
has(key: PropertyKey): boolean {
return this.items.hasOwnProperty(key);
}
// 通过key获取字典上对应的值
get(key: PropertyKey): any {
return this.items[key];
}
// 返回字典中元素的个数
size(): number {
return this.keys().length;
}
// 返回字典中key组成的数组
keys(): string[] {
return Object.keys(this.items);
}
// 返回字典中value组成的数组
values(): any[] {
return Object.values(this.items);
}
}
5. 测试方法
const map = new _Map();
map.set('a', 'a');
console.log(map.keys()); // ['a']
map.set('a', 'a');
console.log(map.keys()); // ['a']
map.set('b', 'b');
console.log(map.size()); // 2
map.set('c', 'c');
console.log(map.keys()); // ['a', 'b', 'c']
console.log(map.get('a'));// 'a'
map.set('1', '1');
map.set('2', '2');
map.set('3', '3');
map.remove('2');
console.log(map.values()); // ['1', '2', '3', 'a', 'b', 'c']
console.log(map.has('a')); // true