简体   繁体   English

克隆对象数组失败

[英]Clone array of objects fails

I fetch some fancy data from an MVC Controller and asign it to the global variable "data_Visits". 我从MVC控制器获取一些奇特的数据,并将其与全局变量“data_Visits”对齐。 Then, later in the party, I need to operate repeatedly on the original data in "data_Visits". 然后,在聚会后期,我需要对“data_Visits”中的原始数据重复操作。

To not change values in "data_Visits", I thought to clone it and then operate on the clone. 为了不改变“data_Visits”中的值,我想克隆它然后对克隆进行操作。 Still, the following seems to change values in "data_Visits": 不过,以下似乎改变了“data_Visits”中的值:

var data = data_Visits.slice(0);

data.forEach(function (d) {
    d.date = new Date(ToJavaScriptDate(d.date));
    d.result1 = +d.result1;
    d.result2 = +d.result2;
});

Would anybody happen to know WHY ? 有人会碰巧知道为什么吗?

Because you're making a clone of an array of references. 因为你正在复制引用数组。 You need to clone each array entry specifically, otherwise both arrays would contain the different collections of references to the same objects. 您需要专门克隆每个数组条目,否则两个数组都将包含对同一对象的不同引用集合。

What you need to do is called a deep copy. 你需要做的是一个深层复制。

As soon as you've specified jquery tag - here is an example: 一旦你指定了jquery标签 - 这是一个例子:

var data = $.extend(true, [], data_Visits);

References: 参考文献:

PS: as a simple example: PS:作为一个简单的例子:

This is what you basically do: 这是你基本上做的:

var a = { foo: 'bar' };
var b = a;

and even though you have 2 variables - they refer to the same object. 即使你有2个变量 - 它们也引用同一个对象。

I agree, extend is what you want. 我同意,延伸就是你想要的。 If you use an array - you can use slice. 如果使用数组 - 可以使用切片。

var d = {bob: 'yes'}
var b = jQuery.extend({}, d);

b.bob = 'no'
// shows b modified, d is not
console.log(b, d);

here is a nice referencde: How do I correctly clone a JavaScript object? 这是一个很好的参考: 如何正确克隆JavaScript对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM