// 创建一个简单的 HashMap 实现
class HashMap {
constructor() {
this.map = new Map(); // 使用 ES6 的 Map 对象来存储键值对
}
// 添加或更新键值对
put(key, value) {
this.map.set(key, value);
}
// 获取指定键的值
get(key) {
return this.map.get(key);
}
// 删除指定键的键值对
remove(key) {
this.map.delete(key);
}
// 检查是否包含某个键
containsKey(key) {
return this.map.has(key);
}
// 获取所有键值对的数量
size() {
return this.map.size;
}
}
// 示例用法
const hashMap = new HashMap();
hashMap.put('name', 'Alice');
hashMap.put('age', 25);
console.log(hashMap.get('name')); // 输出: Alice
console.log(hashMap.containsKey('age')); // 输出: true
hashMap.remove('age');
console.log(hashMap.containsKey('age')); // 输出: false
console.log(hashMap.size()); // 输出: 1
HashMap
类,内部使用 ES6 的 Map
对象来存储键值对。通过这些方法,我们可以方便地操作键值对数据。
上一篇:js map使用
下一篇:js string转对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站