Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

Looping through 2d Typescript array and making new array from value at index

I have the following array in Typescript:

this.days_in_month = [
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
    [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
];

I want to loop through it, and for every value create a new, empty, array of length of that value and add that array to another array of arrays.

Eg: the first value is 31 so I would create an empty array 31 things long and add the 31-array to an array of arrays. The next value is 28 so I would then create an array 28 things long and then add the 28-array to the array of arrays so that it now contains the 31-array and the 28-array.

In Python I would use range, but I'm not sure how to do this in Typescript.

So far I have the following ts:

this.days_in_month.forEach(function(value, index, array) {
    console.log(value, index, array);
    no_of_days: number = this.days_in_month(value);
    let days = new Array<number>(no_of_days);
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Array.prototype.map:

let result = days_in_month.map(
    year => year.map(
        (days) => new Array(days)
    )
);

Bear in mind, the created arrays have undefined values. You would typically generate the required values of the array instead of just initializing an empty array for each month.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...