Reputation: 219
I am looking for an array declaration, initialisation and access for an array which will have the
An table/Array(with its rows) will look like this:
CusomClass1Instance;Number;CusomClass2Instance
CusomClass1Instance;Number;CusomClass2Instance
CusomClass1Instance;Number;CusomClass2Instance
CusomClass1Instance;Number;CusomClass2Instance
...
I used to declare it like this:
let result: [CusomClass1Instance, Number, CusomClass2Instance][]
To initialise i tried something like this:
result= [[new CusomClass1Instance(_id)], [new Number()], [new CusomClass2Instance(_id)]][];
And I have trouble(in this case) to: 1. initialise it empty 2. write to it(using push, index) 3. access it
Thank you, in advance.
Upvotes: 0
Views: 253
Reputation: 95614
let result: [CusomClass1Instance, Number, CusomClass2Instance][]
This is an array of "tuples", which Typescript uses to mean a fixed-length array with potentially different types for each element. Each element of the outer array is an array that has three elements: CusomClass1Instance, Number, and CustomClass2Instance. This makes it an array of arrays, but the outer array has one element per row.
// incorrect
result=[[new CusomClass1Instance(_id)], [new Number()], [new CusomClass2Instance(_id)]][];
Here you are assigning it to a three-element array, where each of the three elements is an array. You also apply an empty set of square brackets at the end, even in your assignment. In any event, this syntax is closer to a different structure where the outer array has one element per column.
Once you've set the array type, Typescript is happy to let you set an empty array as an initializer:
result = [];
If you want to initialize it non-empty, you can do that too, but you have to assign it to an array of three-element arrays:
result = [[new CusomClass1Instance(_id), new Number(), new CusomClass2Instance(_id)]];
Note that you're using two sets of square brackets: The outer brackets are for the array of tuples, and the inner bracket to define a tuple. Note also that you probably don't need to call new Number()
, but instead can just pass the number itself:
result = [
[new CusomClass1Instance(id1), 1, new CusomClass2Instance(id1)],
[new CusomClass1Instance(id2), 2, new CusomClass2Instance(id2)]
];
You can push to the result array, but you need to make sure that each element you push is a matching three-element tuple.
result.push([new CusomClass1Instance(_id), new Number(), new CusomClass2Instance(_id)]);
This also applies when you access it:
let threeElementArray = result[index];
threeElementArray[0] // CusomClass1Instance
threeElementArray[1] // number
threeElementArray[2] // CusomClass2Instance
And you can use unpacking/destructuring syntax to make this easy:
let [class1, yourNumber, class2] = result[index];
// Now you have one variable per value, without defining an explicit
// threeElementArray variable.
Upvotes: 1