Angular JS:当对象引用另一个对象时,angular.copy会使浏览器崩溃

时间:2020-12-25 21:17:52

I have the following JavaScript/Angular code:

我有以下JavaScript / Angular代码:

var a = {};
var b = {};
a.ref = b;
b.ref = a;
angular.copy(a);

When angular.copy fires, the browser locks up. I'm assuming this is because the copy function is doing a deep copy, and when it starts to copy a's reference of b, it goes into b and then wants to copy its reference of a, thus creating a circular copy, which will never end.

当angular.copy触发时,浏览器会锁定。我假设这是因为复制函数正在进行深层复制,当它开始复制b的引用时,它进入b然后想要复制它的引用,从而创建一个圆形副本,这将永远不会结束。

Is this assumption right? If so, is there a way to avoid this? I'm assuming the answer will involve changing the way my data looks, but I'm curious to hear another person's thoughts.

这个假设是对的吗?如果是这样,有没有办法避免这种情况?我假设答案将涉及改变数据的外观,但我很想听到另一个人的想法。

2 个解决方案

#1


2  

Your assumption is right, the problem is the circular reference. JSON.stringify will also complain about this structure. jQuery.extend detects circular references at a very basic level and can handle your basic example here, but jQuery.extend has its own issues as well. If you're already using jQuery, you can just use extend, but otherwise you may want to look at writing something yourself, or you can use this fancy cloneObject function I found via Google:

你的假设是对的,问题是循环引用。 JSON.stringify也会抱怨这个结构。 jQuery.extend在非常基本的级别检测循环引用,并且可以在这里处理你的基本示例,但是jQuery.extend也有自己的问题。如果你已经在使用jQuery,你可以使用extend,但是你可能想看看自己写的东西,或者你可以使用我通过Google找到的这个花哨的cloneObject函数:

https://gist.github.com/NV/1396086

#2


1  

_.cloneDeep handles circular references. http://lodash.com/

_.cloneDeep处理循环引用。 http://lodash.com/

#1


2  

Your assumption is right, the problem is the circular reference. JSON.stringify will also complain about this structure. jQuery.extend detects circular references at a very basic level and can handle your basic example here, but jQuery.extend has its own issues as well. If you're already using jQuery, you can just use extend, but otherwise you may want to look at writing something yourself, or you can use this fancy cloneObject function I found via Google:

你的假设是对的,问题是循环引用。 JSON.stringify也会抱怨这个结构。 jQuery.extend在非常基本的级别检测循环引用,并且可以在这里处理你的基本示例,但是jQuery.extend也有自己的问题。如果你已经在使用jQuery,你可以使用extend,但是你可能想看看自己写的东西,或者你可以使用我通过Google找到的这个花哨的cloneObject函数:

https://gist.github.com/NV/1396086

#2


1  

_.cloneDeep handles circular references. http://lodash.com/

_.cloneDeep处理循环引用。 http://lodash.com/