discoverx

博客园 首页 新随笔 联系 订阅 管理

TypeScript中做类似ActionScript中的Dictionary功能时的写法

var dict: { [index: string]: Function[]; } = {};
遍历

for(let k in dict){consle.log(dict[k]);}
 selectBigPartBody: { [key: string]: string }
//add
 selectBigPartBody[key] = 'value';

我们可以自定义一个字典类

export default class Dictionary {
  items: object;
  constructor() {
    this.items = {};
  }
  has(key: any): boolean {
    return this.items.hasOwnProperty(key);
  }
  set(key: any, val: any) {
    this.items[key] = val;
  }
  delete(key: any): boolean {
    if (this.has(key)) {
      delete this.items[key];
    }
    return false;
  }
  get(key: any): any {
    return this.has(key) ? this.items[key] : undefined;
  }
  values(): any[] {
    const values: any[] = [];
    for (const k in this.items) {
      if (this.has(k)) {
        values.push(this.items[k]);
      }
    }
    return values;
  }
}
 
// 使用如下
 
posted on 2021-12-23 16:30  discoverx  阅读(301)  评论(0)    收藏  举报