R01*_*010 11 javascript clone copy node.js lodash
我有
config.default_req = { foo: 'foo' }
this.default_req = _.clone(config.default_req);
this.default_req.body.data = 'bar';
Run Code Online (Sandbox Code Playgroud)
现在config.default_req.data等于'bar',为什么?,我认为用lodash进行克隆应该只是复制对象,丢失任何与原始对象的链接!
有关如何在node.js中真正克隆/复制对象的任何想法?(v.0.10.40)
编辑:对于那些将要解决这个问题的人来说,一个简单的克隆/复制功能:
var clone = function(source){
return JSON.parse(JSON.stringify(source));
};
Run Code Online (Sandbox Code Playgroud)
Dua*_*ane 15
这是因为clone浅拷贝.你应该使用cloneDeep.
请查看参考资料:https://lodash.com/docs#cloneDeep
浅拷贝只会复制对象的每个属性上的数据.因此,数组和对象通过引用传递.浅拷贝相对较快.另一方面,深层副本递归地沿着树向下移动,因此对象和数组是新实例.深拷贝相对较慢,因此除非需要,否则要小心使用它们.
您可以在这里查看它:https://jsfiddle.net/qqnved24/2/
尝试使用以下内容:
var myObj = {
arr: [1, 2, 3],
obj: {
first: 'foo'
}
}
var myDeepClone = _.cloneDeep(myObj)
var myShallowClone = _.clone(myObj)
//Should ONLY change array slot 1 on my Clone
myDeepClone.arr[1] = 99
console.log(' ==== Checking Deep Clone Array ==== ')
console.log(myObj)
console.log(' -- Deep Clone Below --');
console.log(myDeepClone)
console.log('\n\n')
// Danger: Will change the 'first' property on both the shallow copy and the original
myShallowClone.obj.first = 'bar';
console.log(' ==== Checking Shallow Clone Obj ==== ')
console.log(myObj)
console.log(' -- Shallow Clone Below --');
console.log(myShallowClone);
console.log('\n\n')
// Should only change the 'first property' on the Deep Cloned Obj
myDeepClone.obj.first= 'myObj';
console.log(' ==== Checking Deep Clone Obj ==== ')
console.log(myObj)
console.log(' -- Deep Clone Below --');
console.log(myDeepClone)
console.log('\n\n')
// Danger will alter Shallow clones OBJ
myObj.obj.meaningOfLife = 42;
console.log(' ==== Mutating Original Obj ==== ')
console.log(myObj)
console.log(' -- Shallow Clone Below --');
console.log(myShallowClone)
console.log(' -- Deep Clone Below --');
console.log(myDeepClone)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13216 次 |
| 最近记录: |