简体   繁体   English

Angular Typescript无法从键值对获取键值

[英]Angular Typescript Can't get the key value from keyvalue pair

I added an array of keyvalue for months. 我添加了几个月的键值数组。

  months : { [key: number]: string } = { 1: 'January', 2: 'February', 3: 'March', 
  4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October',
  11: 'November', 12: 'December' } 

I can get the value without any issues 我可以毫无问题地获得价值

var firstMonth= this.months[0].valueOf(); var firstMonth = this.months [0] .valueOf();

However, I can't get the key value. 但是,我无法获取键值。

I tried this.months[0].key. 我尝试了this.months [0] .key。 this does not work 这不起作用

When I used var firstMonth = this.months[0] , I only see the value of 'January'. 当我使用var firstMonth = this.months [0]时,我只看到'January'的值。 I don't see the keyvalue when accessing one of the element in the array. 访问数组中的元素之一时,我看不到键值。 When I hover over the array, I see all the months with both key values. 当我将鼠标悬停在数组上时,会看到所有月份都有两个键值。

I see the example of using *ngFor in stackblitz for angular6-keyvaluepipe-demo but I can't access the key value in the typescript file. 我看到了在angularbl-keyvaluepipe-demo的stackblitz中使用* ngFor的示例,但是我无法访问打字稿文件中的键值。

Any help is appreciated. 任何帮助表示赞赏。

Take a look at using Object.keys(this.months) . 看一下使用Object.keys(this.months)

While this may look very similar to key/value pairs, it's actually a form of indexing. 尽管这看起来与键/值对非常相似,但它实际上是索引的一种形式。

If you want to have key/value behavior out of the box, you should look at using a Map<number, string> . 如果要立即使用键/值行为,则应使用Map<number, string>

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

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