簡體   English   中英

打字稿map.get返回未定義

[英]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"));

檢查一下: https : //jsfiddle.net/vipinmpd08/1b68eLdr/91920/

你搞砸了很多事情。

  1. 即使您聲明了Map類型,您也分配了一個Array值。
  2. 該數組是對象的數組,而不是長度為2的數組的數組,等等。

有效的地圖創建應如下所示:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM