跟集合类似,只是key发生了变化
'use strict';
class Directionary {
// 构建函数
constructor () {
this.items = {}
}
// create / change a new / old value
set (key, value) {
this.items[key] = value;
return true
}
// delete a old value
remove (key) {
if (this.has(key)) {
delete this.items[key]
console.log('删除成功');
return true
}
return false
}
// confirm
has (key) {
return key in this.items
}
// get the value of key
get (key) {
// let a = this.items[key]
// console.log('aaaa:' + a);
return this.items[key] ? this.items[key] : undefined
}
// clear all items
clear () {
this.items = {}
return 'clear is ok!'
}
// show how many items in the directionary
size () {
return Object.keys(this.items).length
}
// show all keys
keys () {
return Object.keys(this.items)
}
// show all values in the key
values () {
let values = []
for(let i in this.items) {
values.push(this.items[i])
}
return values
}
}
let directionary = new Directionary ()
let temp;
directionary.set(1, 1)
directionary.set(2, 3)
temp = directionary.has(1)
console.log('=====================');
console.log('1.TEST1: has()');
console.log(temp);
console.log('=====================');
console.log('2. TEST2: values()');
temp = directionary.values()
console.log(temp);
console.log('=====================');
console.log('3. TEST3: keys()');
temp = directionary.keys()
console.log(temp);
console.log('=====================');
console.log('4. TEST4: size()');
temp = directionary.size()
console.log(temp);
// console.log('=====================');
// console.log('5. TEST5: clear()');
// temp = directionary.clear()
// console.log(temp);
console.log('=====================');
console.log('6. TEST6: get()');
temp = directionary.get(2)
console.log(temp);
console.log('=====================');
console.log('7. TEST7: remove()');
temp = directionary.remove(1)
console.log(temp);
console.log('=====================');