简体   繁体   English

Typescript-初始化嵌套的哈希对象

[英]Typescript - initialize nested hash object

I'm kinda new on typescript, and I really don't know how to approach this: I wanna initialize a hash object with 0 values... something like that: 我对Typescript有点陌生,我真的不知道该如何处理:我想用0值初始化一个哈希对象……

let values;

for(let year of this.years_collection){
    for(let month of this.months_collection){
        this.values[year][month] = 0;
    }
}

But this syntax is clearly invalid. 但是这种语法显然是无效的。 How could I do that, in a way that I would get a nested hash with my month and years, all then with 0 values seted? 我如何才能做到这一点,以使我的月份和年份得到嵌套的哈希,然后全部设置为0值? Thanks in advance! 提前致谢!

Something like this: 像这样:

let values = {} as {
    [key: string]: { [key: string]: number };
};

for (let year of this.years_collection) {
    for (let month of this.months_collection) {
        if (!this.values[year]) {
            this.values[year] = {}
        }

        this.values[year][month] = 0;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM