Javascript:TypeError:循环对象值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32334580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:07:40  来源:igfitidea点击:

Javascript: TypeError: cyclic object value

javascriptjson

提问by Neil P

I am trying to stringify a javascript object, however when I do this a get the following error:

我正在尝试对一个 javascript 对象进行字符串化,但是当我这样做时,会出现以下错误:

TypeError: cyclic object value

类型错误:循环对象值

I don't believe that my code contains any cyclic references (newServiceObject is not referenced inside the object), so I do not understand why I am getting this message.

我不相信我的代码包含任何循环引用(对象内部没有引用 newServiceObject),所以我不明白为什么我会收到这条消息。

I want to turn my object that contains two properties and an array into a single string.

我想将包含两个属性和一个数组的对象转换为单个字符串。

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);

The error occurs on the last line (the JSON.Stringify() ) but I have no idea why!

错误发生在最后一行( JSON.Stringify() ),但我不知道为什么!

采纳答案by Juan Mendes

This is typically because you are trying to serialize a JavaScript object that has properties that point to each other in a cycle.

这通常是因为您试图序列化一个 JavaScript 对象,该对象的属性在一个循环中相互指向。

In your example, newServiceObject.serviceCodeElemListpoints to a jQueryobject which does have cycles in it: Its contextproperty which points to a document object. A document object has pointers to DOM elements that have pointers back to the document through the ownerDocumentproperty

在您的示例中,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>

回答by Neil P

Found it!

找到了!

My problem was that when using jquery to build the array, I should have included the ToArray() method after the map function.

我的问题是,当使用 jquery 构建数组时,我应该在 map 函数之后包含 ToArray() 方法。

    var serviceCodeElemList = $(".ServiceCodeName").map(function() { return $(this).html(); } ).ToArray();

Therefore when the array is included in the object, it is a standard array and not a jquery object.

因此,当数组包含在对象中时,它是一个标准数组,而不是一个 jquery 对象。