如何显示JavaScript ES6映射对象到控制台? [英] How can I Display a JavaScript ES6 Map Object to Console?
问题描述
我正在使用 repl.it/languages/javascript .
在打印出来之前是否必须将其转换为对象?
Do I have to convert it to an object before I print it out?
我尝试过
const mapObject = new Map();
mapObject.set(1, 'hello');
console.log(JSON.stringify(mapObject));
console.log(mapObject);
结果始终是空对象.
当我使用
console.log([...mapObject]);
它打印出数组格式.
推荐答案
注意:此答案仅与OP正在使用的repl.it沙箱环境有关
由于您在评论中说您正在使用 repl.it ,所以您有一个窍门可以用来编写自己的日志记录策略".
Since you said in the comments that you're using repl.it, there's a trick you can use to write your own "logging strategy".
请注意,您不应在生产中使用此技巧,主要是因为它可以编辑本机原型.在某些Node环境中,在您自己的代码中,它可能会很有用.
Note that you shouldn't use this trick in production, mainly because it edits a native prototype. In some Node environment, in your own code, it could be useful though.
这个想法是为 Map
创建一个 inspect
方法,该方法在 entries
上进行迭代:
The idea is to create an inspect
method for Map
that iterates over the entries
:
Map.prototype.inspect = function() {
return `Map(${mapEntriesToString(this.entries())})`
}
function mapEntriesToString(entries) {
return Array
.from(entries, ([k, v]) => `\n ${k}: ${v}`)
.join("") + "\n";
}
您可以看到repl.it支持它 此处
You can see that repl.it supports it here
console.log(new Map([["a", 1], ["b", 2]]));
// Logs:
/*
Map(
a: 1
b: 2
)
*/
这篇关于如何显示JavaScript ES6映射对象到控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!