我在Typescript编译器的代码中看到了"HashTable"的实现(在文件src/compiler/core/hashTable.ts中).
你知道有没有办法直接在我的Typescript项目中使用它?
Ros*_*ott 18
您可以通过定义接口来实现一个非常简单的哈希表,其中键是一个字符串
class Person {
name: string;
}
interface HashTable<T> {
[key: string]: T;
}
var persons: HashTable<Person> = {};
persons["bob"] = new Person();
var bob = persons["bob"];
Run Code Online (Sandbox Code Playgroud)
它只能键入字符串或数字.
下载文件“hashTable.ts”并将其放在您的文件旁边。然后在文件顶部执行以下操作:
///<reference path='hashTable.ts' />
Run Code Online (Sandbox Code Playgroud)
PS:我建议您查看我编写的库 TypeScript Generic Collections。这是一个字典示例:
class Person {
constructor(public name: string, public yearOfBirth: number,public city?:string) {
}
toString() {
return this.name + "-" + this.yearOfBirth; // City is not a part of the key.
}
}
class Car {
constructor(public company: string, public type: string, public year: number) {
}
toString() {
// Short hand. Adds each own property
return collections.toString(this);
}
}
var dict = new collections.Dictionary<Person, Car>();
dict.setValue(new Person("john", 1970,"melbourne"), new Car("honda", "city", 2002));
dict.setValue(new Person("gavin", 1984), new Car("ferrari", "F50", 2006));
console.log("Orig");
console.log(dict);
// Changes the same john, since city is not part of key
dict.setValue(new Person("john", 1970, "sydney"), new Car("honda", "accord", 2006));
// Add a new john
dict.setValue(new Person("john", 1971), new Car("nissan", "micra", 2010));
console.log("Updated");
console.log(dict);
// Showing getting / setting a single car:
console.log("Single Item");
var person = new Person("john", 1970);
console.log("-Person:");
console.log(person);
var car = dict.getValue(person);
console.log("-Car:");
console.log(car.toString());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12110 次 |
| 最近记录: |