简体   繁体   English

map.get 不是 function,同时从 map 中的 map 检索值

[英]map.get is not a function while retrieving a value from a map in typescript

I am having a map with key and value as strings.我有一个 map,键和值作为字符串。 However when trying to retrieve a value based on the key it is throwing error.但是,当尝试根据键检索值时,它会引发错误。

the following is my code snippet.以下是我的代码片段。

let map:Map<string, string> =  {  [ "key1": "hello world 1" ], ["key2": "hello world 2"] } ;
alert( JSON.stringify(map.get("key"))  );

the exception i got below is as follows.我在下面得到的例外如下。

VM133:4 Uncaught TypeError: map.get is not a function
    at eval (eval at exec (typescript.js:41), <anonymous>:4:26)
    at exec (typescript.js:41)
    at HTMLDocument.runScripts (typescript.js:41)

appreciate if you can tell me what am I doing wrong感谢您能告诉我我做错了什么

thank you谢谢你

A Map is not a primitive and needs to be called with the constructor (I think Typescript should have warned about this). Map不是原语,需要使用构造函数调用(我认为 Typescript 应该对此提出警告)。

See the MDN documentation for Map请参阅Map的 MDN 文档

You're probably looking for this:你可能正在寻找这个:

const map:Map<string, string> = new Map([
  [ "key1", "hello world 1" ], 
  [ "key2", "hello world 2" ],
])

I think you should create a map like this in typescript, you're missing the constructor call.我认为你应该在 typescript 中创建一个像这样的 map,你错过了构造函数调用。 What you've right now is just an object literal that is also formatted in a wrong way.你现在所拥有的只是一个 object 文字,它的格式也是错误的。

let myMap = new Map([
        ["key1", "value1"],
        ["key2", "value2"]
    ]);
alert( JSON.stringify(map.get("key1"))  );

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

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