【问题标题】:Is there any defined HashTable class in TypeScript like C#TypeScript 中是否有任何已定义的 HashTable 类,例如 C#
【发布时间】:2019-06-30 02:26:50
【问题描述】:

我正在使用 TypeScript 开发 Web 项目。这里我需要像 C# HashTable 这样的打字稿中的 HashTable 功能。但我已经在 JavaScript 中开发了它。

        this.length = 0;
    this.items = [];
    this.add = function (key, value) {
        this.previous = undefined;
        if (this.containsKey(key)) {
            this.previous = this.items[key];
        } else {
            this.length++;
        }
        this.items[key] = value;
        return this.previous;
    };
    this.clear = function () {
        this.items = {};
        this.length = 0;
    };
    this.contains = function (key) {
        return this.items.hasOwnProperty(key);
    };
    this.containsKey = function (key) {
        return this.items.hasOwnProperty(key);
    };
    this.containsValue = function (key) {
        return (this.items.hasOwnProperty(key) && this.items[key] != undefined) ? true : false;
    };
    this.getItem = function (key) {
        if (this.containsKey(key))
        {

            return this.items[key]
        }
        else
        {
            return  undefined;
        }
    };
    this.keys = function () {
        var keys = [];
        for (var k in this.items) {
            if (this.containsKey(k)) {
                keys.push(k);
            }
        }
        return keys;
    };
    this.remove = function (key) {
        if (this.containsKey(key)) {
            this.previous = this.items[key];
            this.length--;
            delete this.items[key];
            return this.previous;
        } else {
            return undefined;
        }
    };
    this.values = function () {
        var values = [];
        for (var k in this.items) {
            if (this.containsKey(k)) {
                values.push(this.items[k]);
            }
        }
        return values;
    };
    this.each = function (fn) {
        for (var k in this.items) {
            if (this.containsKey(k)) {
                fn(k, this.items[k]);
            }
        }
    };
    var previous = undefined;
}
return HashTable;

像这样,Typescript 有预定义的代码?或者我需要将这些代码从 JS 重写为 TS?打字稿中这个 HashTable 是否有任何简单的属性或类?

或 TS 中的任何其他属性来执行相同的 HashTable 功能?

【问题讨论】:

标签: javascript typescript hashtable typescript2.0


【解决方案1】:

现代 JavaScript 有三种选择:

  • Map,据我所知最接近 HashTable。它的主要优点是它的密钥可能是Object 类型。
  • Set,基本上就是一个唯一的数组。
  • Object 也称为 {}。键值存储。

我建议使用对象,但如果您的键需要是对象,请使用Map


JavaScript Object{}Map 快大约 20 倍。所以只有在需要使用对象作为键时才使用Map

【讨论】:

  • 是否可以使用您建议的地图对象将我的 JS 代码转换为 TS?
  • @Raja 我不太明白你的问题...要将 JS 转换为 TS,只需重命名文件并设置编译即可。
【解决方案2】:

Map 可能是上面建议的正确答案,但也许带有类型的 hashmap 看起来像这样可以工作:

{ [key: string]: Type; }

or

{ [key: number]: Type; }

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    相关资源
    最近更新 更多