洛达什 | _.cloneDeep() 方法
_.cloneDeep() 方法用于创建该值的深层副本,即它递归地克隆该值。此方法类似于 _.clone() 方法。
句法:
_.cloneDeep( value )
参数:此方法接受上面提到的单个参数,如下所述:
- value:该参数保存需要递归克隆的值。
返回值:此方法返回深度克隆值。
示例 1:克隆简单对象
Javascript
const _ = require('lodash');
var obj = {
x: 23
};
// Deep copy
var deepCopy = _.cloneDeep(obj);
console.log('Comparing original with'
+ ' deep ', obj === deepCopy);
obj.x = 10; // Changing original value
console.log('After changing original value');
console.log("Original value ", obj);
console.log("Deep Copy value ", deepCopy);
Javascript
const _ = require('lodash');
var obj = [{ x: 1 }, {y: 2}];
// Deep copy
var deepCopy = _.cloneDeep(obj);
console.log('Comparing original with deep ',
obj[0] === deepCopy[0]);
// Changing original value
obj[0].x = 10;
// Values after changing original value
console.log("After changing original value");
console.log("Original value ", obj);
console.log("Deep Copy value ", deepCopy);
输出:
Comparing original with deep false
After changing original value
Original value { x: 10 }
Deep Copy value { x: 23 }
示例 2:克隆复杂对象
Javascript
const _ = require('lodash');
var obj = [{ x: 1 }, {y: 2}];
// Deep copy
var deepCopy = _.cloneDeep(obj);
console.log('Comparing original with deep ',
obj[0] === deepCopy[0]);
// Changing original value
obj[0].x = 10;
// Values after changing original value
console.log("After changing original value");
console.log("Original value ", obj);
console.log("Deep Copy value ", deepCopy);
输出:
Comparing original with deep false
After changing original value
Original value [ { x: 10 }, { y: 2 } ]
Deep Copy value [ { x: 1 }, { y: 2 } ]
因此,在这里我们已经看到,在更改原始值之后,值的深层副本并没有改变,因为 _.cloneDeep() 递归地深度复制了值。
注意:这在普通 JavaScript 中不起作用,因为它需要安装库 lodash。
参考: https://lodash.com/docs/4.17.15#cloneDeep