在我的 angular2 应用程序中,我想创建一个以数字为键并返回对象数组的映射。我目前正在以下列方式实施,但没有运气。我应该如何实现它或者我应该为此目的使用其他一些数据结构?我想使用地图,因为它可能很快?
宣言
private myarray : [{productId : number , price : number , discount : number}];
priceListMap : Map<number, [{productId : number , price : number , discount : number}]>
= new Map<number, [{productId : number , price : number , discount : number}]>();
用法
this.myarray.push({productId : 1 , price : 100 , discount : 10});
this.myarray.push({productId : 2 , price : 200 , discount : 20});
this.myarray.push({productId : 3 , price : 300 , discount : 30});
this.priceListMap.set(1 , this.myarray);
this.myarray = null;
this.myarray.push({productId : 1 , price : 400 , discount : 10});
this.myarray.push({productId : 2 , price : 500 , discount : 20});
this.myarray.push({productId : 3 , price : 600 , discount : 30});
this.priceListMap.set(2 , this.myarray);
this.myarray = null;
this.myarray.push({productId : 1 , price : 700 , discount : 10});
this.myarray.push({productId : 2 , price : 800 , discount : 20});
this.myarray.push({productId : 3 , price : 900 , discount : 30});
this.priceListMap.set(3 , this.myarray);
this.myarray = null;
如果我使用 this.priceList.get(1);
,我想获得一个包含 3 个对象的数组
原文由 usmanwalana 发布,翻译遵循 CC BY-SA 4.0 许可协议
首先,为您的对象定义一个类型或接口,这将使事情更具可读性:
您使用 了大小为 1 的元组 而不是数组,它应该如下所示:
所以现在这工作正常:
( 操场上的代码)