javascript'对象数组'复制后也改变原始数组

时间:2017-07-14 05:07:20

标签: javascript jquery object javascript-objects

我创建了一个名为features的对象数组。然后我试图复制变量new_array。

   var features = mapport.panels.info.current.features();
   console.log(typeof features);
   new_array = features.slice(0);   //new_array is copy of this

另外一种方法也是这样的

var new_array = $.map(features, function (obj) {
     return $.extend({}, obj);
     });

在此之后我将new_array与数组进行比较并删除不常见的条目因此在比较后我喜欢

delete new_array[i].attributes.fields[f_index]

从new_array删除特定索引值后没有问题,它也会从features删除。

如何防止这种情况?

演示示例:



var features = [{
  attributes: {
    fields: ["feat1", "feat2"]
  }
}, {
  attributes: {
    fields: ["feat3", "feat4"]
  }
}]

console.log(typeof features);

// This one works!
var new_array0 = $.map(features, function(obj) {
  return $.extend(true, {}, obj); // deep clone
});
delete new_array0[1].attributes.fields[0]
document.write(JSON.stringify(new_array0)+'<br>'+JSON.stringify(features)+'<hr>')


// these make shallow copies

var new_array = features.slice(0); //new_array is copy of this
delete new_array[1].attributes.fields[0]

document.write(JSON.stringify(new_array)+'<br>'+JSON.stringify(features)+'<hr>')

var new_array1 = $.map(features, function(obj) {
  return $.extend({}, obj);
});
delete new_array1[1].attributes.fields[0]
document.write(JSON.stringify(new_array1)+'<br>'+JSON.stringify(features))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

0 个答案:

没有答案