Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 创建泛型类以使用typescript保存键值数组(字典)_Angular_Typescript_Angular7_Typescript Generics - Fatal编程技术网

Angular 创建泛型类以使用typescript保存键值数组(字典)

Angular 创建泛型类以使用typescript保存键值数组(字典),angular,typescript,angular7,typescript-generics,Angular,Typescript,Angular7,Typescript Generics,我想添加字典类以便在我的应用程序中使用。 我创建了一个类,并向其中添加了一个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>{

我想添加字典类以便在我的应用程序中使用。 我创建了一个类,并向其中添加了一个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> = ...;
导出类KeyValuePair{
键:TKey;
价值:TVal;
构造函数(键:TKey,val:TVal){
this.key=key;
this.value=val;
}
导出类词典{
数组:数组
}
让我的ClassInstance:Dictionary=。。。;
问题:

  • 我希望能够使用forEach或以myClassInstance的let x的形式在循环中对其进行迭代。我如何才能做到这一点?(myClassInstance.forEach(…);)
  • 我可以使用类实例来获取数组而不调用className.arrayName吗?(myClassInstance.find(…);)
  • 我可以使用类实例作为索引来获取值吗?(myClassInstance[1])
    • 如果有更好的结构吗?我想听听并学习。。。 谢谢
      • 看看,它们是字典

        您可以这样使用它们:


        您可以迭代它们的值、键或条目,然后键入它们。您可以使用get查找内容。您可以将它们转换为数组[…myMap.values()],注意:它们将按键插入顺序排序。(您可以改为使用entries(),然后根据需要将结果映射为按键排序)

        既然你的键都是数字,它们都是有效的对象键,为什么不使用一个普通的javascript对象呢?你可以用类型记录来描述它。@LindaPaiste-使用记录而不是数组会有什么损失吗?我也不知道什么效率更高,因为我将在数组上使用find,索引更好吗?你有吗实现演示?