[英]Typescript map.get return undefined
When I want get Object
by key
I have undefined
each all element. 当我想通过key
获取Object
,我没有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
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/ 检查一下: https : //jsfiddle.net/vipinmpd08/1b68eLdr/91920/
You've messed many things. 你搞砸了很多事情。
Map
, you assigned an Array
value. 即使您声明了Map
类型,您也分配了一个Array
值。 Valid map creation should look like this: 有效的地图创建应如下所示:
let nodesMap = new Map([ [1, 'foo'], [2, 'bar'], [3, 'baz'], ]) console.log(nodesMap.get(1)) // foo
You can't assign properties on top of the fact they aren't objects, they are arrays, and you need to use new
. 您不能基于属性不是对象,它们是数组的事实来分配属性,而需要使用new
。 Your code should look like: 您的代码应如下所示:
// 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.