TypeScript - 数组中的数组 - 将新对象推送到特定数组

时间:2016-08-22 15:22:21

标签: javascript typescript visual-studio-2015

我认为是2D阵列,通过以下方式生成。

export class ItemClass
{
    ItemId: number;
    Name: string;
    Units: number;
}
var masterItemArray: any[] = [];

var itemArray: ItemClass[] = [];

let item: ItemClass;

item = new ItemClass();
item.ItemId = 100;
item.Name = "Item 1";
item.Units = 2;
itemArray.push(item);

item = new ItemClass();
item.ItemId = 100;
item.Name = "Item 2";
item.Units = 5;
itemArray.push(item);

masterItemArray.push(itemArray);

var itemArray1: ItemClass[] = [];

item = new ItemClass();
item.ItemId = 200;
item.Name = "Item 1";
item.Units = 4;
itemArray1.push(item);

item = new ItemClass();
item.ItemId = 200;
item.Name = "Item 2";
item.Units = 8;
itemArray1.push(item);

masterItemArray.push(itemArray1);

然后创建一个2D数组,如下面的

[
    {
       {ItemId = 100, Name = "Item 1", Units = 2},
       {ItemId = 100, Name = "Item 2", Units = 5}
    },
    {
       {ItemId = 200, Name = "Item 1", Units = 4},
       {ItemId = 200, Name = "Item 2", Units = 8}
    }
]

我的问题是我希望能够推送另一个ItemClass对象来说明数组中的第二个数组(ItemId = 200),例如..

[
    {
       {ItemId = 100, Name = "Item 1", Units = 2},
       {ItemId = 100, Name = "Item 2", Units = 5}
    },
    {
       {ItemId = 200, Name = "Item 1", Units = 4},
       {ItemId = 200, Name = "Item 2", Units = 8},
       {ItemId = 200, Name = "Item 3", Units = 15}
    }
]

但我似乎无法获得正确的代码来推动这一点,例如......

var newItemArray= new Item();
newItemArray.ItemId = 200;
newItemArray.Name = "Item 3";
newItemArray.Units = 15;

masterItemArray[1].push(newItemArray);
尽管引用了正确的索引,

仍然无效。

我不确定还能做些什么,因为使用intellisense时,提供的唯一选项是重命名ItemIdNameUnits等属性,我不是提供了任何数组扩展。

三江源!

0 个答案:

没有答案