![](/img/trans.png)
[英]Using Map.get() method in typescript, returns undefined, while I am handling undefined
[英]Typescript map.get return undefined
当我想通过key
获取Object
,我没有undefined
所有元素。
我的地图:
nodesMaps : Map<number, Object> = [
{ key: "1", value: Object },
{ key: "2", value: Object },
{ key: "3", value: Object },
]
当我想获取这张地图的价值时:
this.nodesMaps.get(1) // return undefined
this.nodesMaps.get("1") // return undefined
下面的代码对我来说..
let map = new Map([
[ "A", "AA" ],
[ "B", "BB" ],
[ "C", "CC" ]
]);
console.log(map.get("A"));
你搞砸了很多事情。
Map
类型,您也分配了一个Array
值。 有效的地图创建应如下所示:
let nodesMap = new Map([ [1, 'foo'], [2, 'bar'], [3, 'baz'], ]) console.log(nodesMap.get(1)) // foo
您不能基于属性不是对象,它们是数组的事实来分配属性,而需要使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.