为什么需要方括号来在Javascript中对Map的所有元素进行字符串化?

Sco*_*ole 6 javascript json brackets stringify ecmascript-6

问题:我似乎无法找到一个令人满意的解释,为什么javascript Maps需要使用方括号来使JSON.stringify方法"到达"(?)到嵌套元素中.我想我错过了关于ES6的一些东西,或Map数据类型固有的东西.

我可以将Map转换为对象,并使用stringify-但为什么这个额外的步骤是必要的?

我的实验:

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?
Run Code Online (Sandbox Code Playgroud)

确认的行为,但并没有解释为什么会发生.

Ry-*_*Ry- 4

JSON.stringify(...blah)参数 spread,它采用迭代地图时获得的值:

\n\n
    \n
  • [\'u\', {\'something\': \xe2\x80\xa6}]
  • \n
  • [{\'hey\': \xe2\x80\xa6}, \'what?\']
  • \n
\n\n

并将它们作为不同的参数传递给JSON.stringify

\n\n
JSON.stringify(\n    [\'u\', {\'something\': \xe2\x80\xa6}],\n    [{\'hey\': \xe2\x80\xa6}, \'what?\']\n);\n
Run Code Online (Sandbox Code Playgroud)\n\n

的第二个参数JSON.stringify 应该是一个替换函数。因为你给了它一些不是函数的东西,所以它会忽略它。

\n\n

争论的传播远不是你想要的。您想要的是将映射转换为键/值对数组,\xe2\x80\x99s 就是这样[...blah]做的。Array.from(blah)会有同样的效果。

\n