15
在我的angular2应用程序中,我想创建一个以数字为键并返回对象数组的映射。我目前正在实施以下方式,但没有运气。我应该如何实现它,或者我应该使用其他一些数据结构来达到这个目的吗?我想使用地图,因为它可能很快?如何定义键值对的Typescript Map。其中键是一个数字,值是一个对象数组
宣言
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);
在你的操场链接在控制台中有一个错误Uncaught TypeError:无法读取未定义(...)的属性“推”我实施它使用一个接口,我得到了同样的错误。 – usmanwalana
这是因为我刚刚复制了你的代码,并且在你的代码中你将'myarray'设置为null,然后尝试推送它。所以要么不要将它设置为null,要么稍后再重新分配一个新的数组。 –
谢谢。这工作。 – usmanwalana