typescript 打字稿 map.get 返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53891026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript map.get return undefined
提问by Matthis.h
When I want get Object
by key
I have undefined
each all element.
当我想要Object
通过时,key
我拥有undefined
每个元素。
My Map :
我的地图:
nodesMaps : Map<number, Object> = [
{ key: "1", value: Object },
{ key: "2", value: Object },
{ key: "3", value: Object },
]
When I want get value of this map :
当我想获得这张地图的价值时:
this.nodesMaps.get(1) // return undefined
this.nodesMaps.get("1") // return undefined
回答by Vipindas Gopalan
below code for me..
下面的代码给我..
let map = new Map([
[ "A", "AA" ],
[ "B", "BB" ],
[ "C", "CC" ]
]);
console.log(map.get("A"));
check this: https://jsfiddle.net/vipinmpd08/1b68eLdr/91920/
回答by Nurbol Alpysbayev
You've messed many things.
你搞砸了很多事情。
- Even if you declared type
Map
, you assigned anArray
value. - The array was array of objects, not array of arrays with length 2. etc.
- 即使您声明了 type
Map
,您也分配了一个Array
值。 - 该数组是对象数组,而不是长度为 2 的数组数组等。
Valid map creation should look like this:
有效的地图创建应如下所示:
let nodesMap = new Map([
[1, 'foo'],
[2, 'bar'],
[3, 'baz'],
])
console.log(nodesMap.get(1)) // foo
回答by Erik Philips
You can't assign properties on top of the fact they aren't objects, they are arrays, and you need to use new
. Your code should look like:
您不能在属性不是对象、它们是数组的基础上分配属性,并且您需要使用new
. 您的代码应如下所示:
// TypeScript
nodesMaps : Map<number, Object> = new Map([
[ 1, Object ],
[ 2, Object ],
[ 3, Object ],
]);
var nodesMaps = new Map([
[ 1, "Object 1" ],
[ 2, "Object 2" ],
[ 3, "Object 3" ],
]);
$('button').on('click', function() {
var key = $(this).data('key');
console.log("key :" + key);
console.log("value: " + nodesMaps.get(key));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-key="1">1</button>
<button data-key="2">2</button>
<button data-key="3">3</button>