class FakeMap {
constructor(arr=[]) {
this.items = {};
this.size = 0;
arr.forEach(item => {
this.set(item[0], item[1]);
});
}
has(val) {
return this.items.hasOwnProperty(val);
}
set(key, val) {
if (this.has(key)) {
this.items[key] = val;
} else {
this.items[key] = val;
this.size++;
}
}
get(key) {
return this.has(key)? this.items[key] : undefined;
}
delete(key) {
if (this.has(key)) {
Reflect.deleteProperty(this.items, key);
this.size--;
return true;
} else {
return false;
}
}
clear() {
this.items = {};
this.size = 0;
}
keys() {
return Object.keys(this.items);
}
values() {
return Object.values(this.items);
}
forEach(fn, context) {
for (let i = 0; i<this.size; i++) {
let key = this.keys()[i];
let value = this.values()[i];
Reflect.apply(fn, context, [key, value]);
}
}
}
let map = new FakeMap([[1, 22], ['3', 44]]);
map.set(true, 'boolean');
map.forEach((key, val) => {
console.log(`${key} : ${val}`);
})
console.log(map)
ES6 Map字典实现
猜你喜欢
转载自blog.csdn.net/roamingcode/article/details/81975913
今日推荐
周排行