TypeScript-入门(九)-自定义字典类

358 阅读1分钟

1.规则

开发一个字典类(Dictionary),字典中会保存键值对的数据

键值对数据的特点:

  • 键(key)可以是任何类型,但不允许重复
  • 值(value)可以是任何类型
  • 每个键对应一个值
  • 所有的键类型相同,所有的值类型相同

字典类中对键值对数据的操作:

  • 按照键,删除对应的键值对
  • 循环每一个键值对
  • 得到当前键值对的数量
  • 判断某个键是否存在
  • 重新设置某个键对应的值,如果不存在,则添加

2.实现

// dictionary.ts

export type Callback<K, V> = (k: K, v: V) => void

export default class Dictionary<K, V> {
    private keys: K[] = [];
    private values: V[] = [];

    // 新增
    set(key: K, val: V) {
        const _index = this.keys.indexOf(key)
        if (_index < 0) {
            this.keys.push(key)
            this.values.push(val)
        } else {
            this.values[_index] = val
        }
    }
    // 判断是否存在key
    has(key: K) {
        return this.keys.includes(key)
    }
    // 循环每个键值对
    forEach(callback: Callback<K, V>) {
        this.keys.forEach((key, index) => {
            callback(key, this.values[index])
        })
    }
    // 获取当前键值对的数量
    get size() {
        return this.keys.length
    }
    // 删除对应的键值对
    delete(key: K) {
        const _index = this.keys.indexOf(key)
        if (_index < 0) return
        this.keys.splice(_index, 1)
        this.values.splice(_index, 1)
    }
}
// index.ts 使用

import Dictionary from "./dictionary";
const dict = new Dictionary<string, string>()

dict.set('name', '张三')
dict.set('age', '12')

dict.forEach((key, val) => {
    console.log(`${key}:${val}`);
})
console.log(dict.size);

dict.delete('age')

dict.forEach((key, val) => {
    console.log(`${key}:${val}`);
})
console.log(dict.size);

image.png