[英]Why are square brackets needed to stringify all elements of a Map in Javascript?
問題:我似乎無法找到一個令人滿意的解釋,為什么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?
本文確認了行為,但沒有解釋為什么會發生這種情況。
JSON.stringify(...blah)
是參數spread ,它接受迭代地圖時得到的值:
['u', {'something': …}]
[{'hey': …}, 'what?']
並將它們作為不同的參數傳遞給JSON.stringify
:
JSON.stringify(
['u', {'something': …}],
[{'hey': …}, 'what?']
);
JSON.stringify
的第二個參數應該是一個replacer函數 。 既然你已經給它了一些不是函數的東西,它就會忽略它。
爭論傳播並不是你想要的遠程。 你想要的是將地圖轉換為鍵/值對的數組,這就是[...blah]
作用。 Array.from(blah)
具有相同的效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.