遍历2d Typescript数组并根据索引处的值创建新数组 [英] Looping through 2d Typescript array and making new array from value at index

查看:46
本文介绍了遍历2d Typescript数组并根据索引处的值创建新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在打字稿中有以下数组:

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.

例如:第一个值是31,所以我将创建一个31东西长的空数组并添加31数组到一个数组的数组。下一个值为28,因此我将创建一个长度为28的数组,然后将28数组添加到数组数组中,使其现在包含31数组和28数组。

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.

在Python中,我会使用range,但是我不确定如何在Typescript中执行此操作。

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);
})


推荐答案

您可以使用 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.

这篇关于遍历2d Typescript数组并根据索引处的值创建新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆