JSON.stringify() 我們很熟悉了,將一個對象轉換為json形式的字符串.
但是如果你在瀏覽器控制台中輸出 JSON.stringify(window). 如果期望輸出一段文字, 可能會失望了. 事實上, 會輸出結果如下:
錯誤信息很明顯了, 對象中有循環引用. 解決方案如下:
參考鏈接:http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json
// Demo: Circular reference
var o = {};
o.o = o;
// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(o, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection
JSON.stringify說明 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
至於出現循環引用的原因,參考如下:
原文鏈接:
http://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json