[英]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.