【问题标题】:get the values of specified key of a map typescript ERROR TypeError: this.trmap.get is not a function获取地图打字稿的指定键的值错误类型错误:this.trmap.get不是函数
【发布时间】:2020-04-24 00:44:55
【问题描述】:

大家好,我应该提到我是打字稿的新手。实际上,我有一个地图,其中数字作为键,数字数组作为值。在我的 html 中,我必须显示所有键,并且根据所做的选择,我必须显示值(键和值都显示为 ion-segment-button)。问题是我无法使用trmap.get(key) 获取任何键的值 here is the error i get in console///////////////// here is the map a par of the json

这是我的 ts 文件:

    trmap: Map<number,number[]>
    values:number[]    

    getSelectedKey(key :number) {
      console.log(key)
      this. values=this.trmap.get(key)
    }

【问题讨论】:

  • 您能否提供在尝试获取值时遇到的错误等?
  • 我做了一个更新,显示控制台中的错误..谢谢你
  • 我现在看到了,get 似乎已定义但不是函数。你确定你拥有的确实是Map
  • @alexortizl 绝对正如我所提到的,我已经使用 "*ngFor="let t of trmap | 显示了按钮中的键。 keyvalue”,我需要显示每个选择的键的值

标签: typescript dictionary ionic-framework


【解决方案1】:

你还没有初始化到 new Map() ,因此你不能使用它的功能。

您可能会在下面的工作代码中找到答案。

class MapTest{

public trmap: Map<number,number[]>  =  new Map<number,number[]>().set(1,[1,2,3,4,5,6,7]);
public values:number[] = [];    

  public getSelectedKey(key :number) {
    console.log(key);
    this.values = this.trmap.get(key) as number[];
    return this.values;
   }

}

const test = new MapTest();
console.log(test.getSelectedKey(1));

【讨论】:

  • 感谢您的时间和帮助,但 trmap 的数据是从 api 服务调用加载的,而不是一些静态数据。我将地图的声明更改为 trmap= new Map() 但我仍然遇到同样的错误
【解决方案2】:

我发现没有必要使用 trmap.get(key)

正如这篇文章中提到的Typescript Map throwing error while using its functions (mapobject.keys() is not a function)

值=trmap[键]

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多