开发者

Why does filtering a new JSON object causes the old one to self-update?

I have a JSON array named arr and a new array named new_arr that is created from arr.

var arr = {"data":
 [
  {"name":"Alan","height":"171","weight":"66"},
  {"name":"Ben","height":"182","weight":"90"},
  {"name":"Chris","height":"163","weight":"71"}
 ]
};

var new_arr = arr;

new_arr.data = jQuery.grep(new_arr.data, function(n, i){
  return n.weight > 70;
});

Both arrays arr and new_arr becomes:

{"data":
 [
  {"name":"Ben","height":"182","weight":"90"},
  {"name":"Chris","height":"163","weight":"71"}
 ]
};

My question is: "Why does modifying the new array changes 开发者_如何学编程the old one?"


There is no new array. It's just a new reference to the old array.
Try it in another example :

var a = {};
var b = a;
// check to see if they are equal
alert(a === b);
// modify one of them 
b.foo = 'bar';
 // check to see if they are equal
alert(a === b);
// modify one of them 
a.bar = 'foo';
 // check to see if they are equal
alert(a === b);

a and b refer to the same object, thus, when you modify a you also modify b and so on.

If you use jquery you should use the extend method :

var new_arr = $.extend(true,arr);


You're referencing the same Array when you do:

var new_arr = arr;

If you want a copy, you need to make a copy:

var new_arr = arr.data.slice( 0 ); // 0 is the optional starting index of the copy

This just makes a shallow copy of the Array, so the nested objects will be referenced by both.

If you need a deep clone of all nested objects, you'd need to traverse into each individual object, and make a copy.


You should clone your array instead. I copied this from John Resig over here. See his post for more explanation.

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

This should work for your arr and new_arr.


may be because arr is an object and var new_arr = arr just assigns reference to it to new_arr ? try this new_arr = arr.clone()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜