【发布时间】:2015-02-08 07:53:38
【问题描述】:
使用一组 Javascript 对象,我想编辑一些值,然后获取一组更改的对象。
a=[{x:1,y:2},{x:2,y:4}];
b = _.clone(a);
// When I change b, a is also changed. I can no longer know the original a.
////////////////////////////////
a=[{x:1,y:2},{x:2,y:4}];
b = _.map( a, _.clone );
// When I change b, a is not changed,
// but I cannot find only the changed JSONs.
// Every JSON between a and b are considered different.
如何实现以下?
a=[{x:1,y:2},{x:2,y:4}];
b = SOME_CLONE_OF_a;
b[0].x=5;
DIFF(b,a) // want to get [{x:5,y:2}]
DIFF(a,b) // want to get [{x:1,y:2}]
[已编辑]
这个问题不是How do you clone an array of objects using underscore?的重复问题
那里提供的答案回答了那个问题(如何克隆),但没有回答我的问题(如何克隆并知道区别)。
这个问题中的DEMO使用了那个答案中的技巧,并证明它找不到想要的差异。
【问题讨论】:
-
当您引用 Javascript 对象时,请停止使用“JSON”。您的问题中没有 JSON。
-
我已经删除了副本。相关阅读:stackoverflow.com/q/13147278,尤其是this answer。