我正在尝试对 javascript 对象进行字符串化,但是当我这样做时出现以下错误:
TypeError: cyclic object value
我不认为我的代码包含任何循环引用(对象内部未引用 newServiceObject),所以我不明白为什么会收到此消息。
我想将包含两个属性和一个数组的对象变成一个字符串。
var serviceName = $('#newServiceNameBox').val();
var serviceCodeElemList = $(".ServiceCodeName").map(function() { return $(this).html(); } );
//create the new service object
var newServiceObject = {ServiceId:-1, ServiceName: serviceName, ServiceCodes: serviceCodeElemList };
var appendNewService = '&newService='+JSON.stringify(newServiceObject);
错误发生在最后一行(JSON.Stringify()),但我不知道为什么!
最佳答案
这通常是因为您正在尝试序列化一个 JavaScript 对象,该对象的属性在一个循环中相互指向彼此。
在您的示例中,newServiceObject.serviceCodeElemList
指向一个 jQuery
对象,其中确实有循环:它的 context
属性指向一个文档对象。文档对象具有指向 DOM 元素的指针,这些元素具有通过 ownerDocument
属性指向文档的指针
var jqueryObj = $('div');
console.log(jqueryObj.context); // Document object
console.log(jqueryObj.context.body.firstChild.ownerDocument); // Document object
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
关于Javascript:TypeError:循环对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334580/