【发布时间】:2018-10-02 09:36:04
【问题描述】:
问题: 我似乎无法找到令人满意的解释,解释为什么 javascript Maps 需要方括号,以便 JSON.stringify 方法“到达”(?)到嵌套元素中。我想我遗漏了一些关于 ES6 的东西,或者 Map 数据类型固有的东西。
我可以将 Map 转换为对象,然后进行字符串化——但为什么需要这个额外的步骤?
我的实验:
const blah = new Map();
blah.set('u', {
'something': [{'hey':98}, 56, 'bob']
});
blah.set({
'hey': {'hey': 78}
}, 'what?');
console.log(JSON.stringify(...blah));
//["u",{}]
//I thought this would yield the result of the below console.log
console.log(JSON.stringify([...blah]))
//[["u",{"something":[{"hey":98},56,"bob"]}],[{"hey":{"hey":78}},"what?"]]
//Why are the square brackets needed to stringify and display each element of
//the map?
article 确认了这种行为,但没有解释为什么会发生。
【问题讨论】:
-
该语法的作用是从地图创建一个数组。
-
地图对象大多(可能总是)字符串化,如
JSON.stringify([...myMap])。
标签: javascript json ecmascript-6 brackets stringify