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