javascript - 为什么需要方括号来将 Javascript 中 Map 的所有元素字符串化?

标签 javascript json ecmascript-6 brackets stringify

问题: 我似乎无法找到一个令人满意的解释,说明为什么 JavaScript map 需要方括号让 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(...blah)argument spread ,它采用迭代 map 时获得的值:

  • ['u', {'something': …}]
  • [{'嘿': …}, '什么?']

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

JSON.stringify(
    ['u', {'something': …}],
    [{'hey': …}, 'what?']
);

JSON.stringify 的第二个参数 is supposed to be a replacer function .因为你给了它一些不是函数的东西,它会忽略它。

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

关于javascript - 为什么需要方括号来将 Javascript 中 Map 的所有元素字符串化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962462/

相关文章:

javascript - 如何在 JavaScript 中检查用户的 asp 成员(member)资格数据库角色?

javascript - 如何使用javascript在文本框中自动显示15天后的日期?

javascript - 如何将 bootstrap-datetimepicker 设置为今天凌晨 12 点的日期

arrays - 在 Init 函数中发出异步 Web 请求 [Swift]

json - curl 以添加索引模式和json文件以创建仪表板

javascript - 如何判断事件是由 .click() 还是用户触发的?

python - json.loads 和 python eval 将字符串转换为 json 对象之间的区别

javascript - 按两个条件的键对对象进行排序,然后按字母顺序排序

javascript - 仅在作用域内附加到字​​符串原型(prototype)的函数

javascript - 为什么 "this"在粗箭头函数定义中未定义?