我创建了JSON对象,在此示例中发生了循环引用错误。 为什么会出现循环引用错误以及如何解决循环引用错误? 提供有关此问题的完整详细信息? 代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
var data = { "Id": 100, "Name": "Name 1", "Children": [{ "Id": 200, "Name": "Name 2", "Children": null }, { "Id": 300, "Name": "Name 3", "Children": null }] };
var record=createRecord(data,null);
JSON.stringify(record);
function createRecord(data,parentItem) {
var record,
childDataSource = data["Children"];
//CLONE THE DATA OBJECT
record = $.extend({}, data);
record.parentItem = parentItem;
record.item = data;
record.childRecords = childDataSource && createChildRecords(childDataSource, record);
return record;
}
function createChildRecords(childDataSource, parentItem) {
var proxy = this,
records = [],
count = 0,
length = childDataSource.length,
record = null,
childRecord;
for (count = 0; count < length; count++) {
record = childDataSource[count];
if (record) {
childRecord = createRecord(record, parentItem);
records.push(childRecord);
}
}
return records;
}
</script>
</body>
</html>
答案 0 :(得分:2)
当你这样做时
record.parentItem = parentItem;
您可以将子对象的链接添加到父对象。
当JSON.stringify
以递归方式迭代对象的属性时,它会从父级循环到子级,再循环到子级的父级,等等。
您无法完全字符串化循环对象。 A&#34;解决方案&#34;将字符串化时使用库忽略属性制作循环,就像我自己的JSON.prune一样。但如果您希望以后能够轻松地从JSON恢复对象,那么这不是一个完整的解决方案。
循环数据结构通常是一种糟糕的设计。