在我的 angular2 应用程序中,我想创建一个以数字为键并返回对象数组的映射。我目前正在以下列方式实现,但没有运气。我应该如何实现它或者我应该为此目的使用其他一些数据结构?我想使用 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);
最佳答案
首先,为您的对象定义一个类型或接口(interface),这将使事情更具可读性:
type Product = { productId: number; price: number; discount: number };
您使用了 a tuple大小为 1 而不是数组,它应该如下所示:
let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
所以现在可以正常工作了:
myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;
关于arrays - 如何定义键值对的 Typescript Map。其中key是一个数字,value是一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40976536/