【发布时间】:2021-02-07 23:56:03
【问题描述】:
我想添加 Dictionary 类以在我的应用程序中使用。 我创建了一个类,并向其中添加了一个 keyValuePair 数组来保存我的列表
export class KeyValuePair<TKey, TVal>{
key:TKey;
value:TVal;
constructor(key:TKey, val:TVal){
this.key = key;
this.value = val;
}
export class Dictionary<TKey, TVal>{
array: Array<KeyValuePair<TKey, TVal>>
}
let myClassInstance:Dictionary<number, string> = ...;
问题:
- 我希望能够使用 forEach 或在循环中作为 let x of myClassInstance 对其进行迭代,我该怎么做? (myClassInstance.forEach(...);)
- 我可以在不调用 className.arrayName 的情况下使用类实例来获取我的数组吗?(myClassInstance.find(...);)
- 我可以使用类实例作为索引来获取值吗?(myClassInstance[1])
- 是否有更好的结构?我想听和学习... 谢谢!!!
【问题讨论】:
-
既然你的键都是数字,它们是有效的对象键,为什么不直接使用一个普通的 javascript 对象呢?您将使用 Record
类型来描述它。 -
@LindaPaiste - 使用记录而不是数组我有什么损失吗?我也不知道什么更有效,因为我将在数组上使用 find,索引更好吗?你有实现演示吗?
标签: angular typescript angular7 typescript-generics