首页 > 解决方案 > 打字稿中的地图初始化

问题描述

我正在尝试在打字稿中初始化下面的地图。当我打印它时,它似乎是空的。

let map: Map<string, object> = new Map<string, object> ([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log(JSON.stringify(map));
// printing {}
// but not the initialized values

标签: javascripttypescript

解决方案


它已正确初始化,但打印它不会像数组一样打印所有值。但是您可以通过访问密钥来检查它 - 它们存在:

let map = new Map([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log(map);
console.log(map.get('api/service/method'));
console.log(map.get('"type": "html"'));

也相关:如何在控制台中显示 javascript ES6 地图对象?

如那里所述,您可以传播地图并打印:

let map = new Map([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log([...map]);


推荐阅读