5

I have the following JavaScript/Angular code:

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.

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.

4

2 回答 2

2

您的假设是正确的,问题是循环引用。JSON.stringify也会抱怨这种结构。 jQuery.extend在非常基本的级别检测循环引用并可以在此处处理您的基本示例,但jQuery.extend 也有其自身的问题。如果您已经在使用 jQuery,则可以使用 extend,否则您可能想自己编写一些东西,或者您可以使用cloneObject我通过 Google 找到的这个奇特函数:

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

于 2013-05-09T14:32:17.057 回答
1

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

于 2014-01-06T21:29:18.060 回答