Lodash .clone 和 .cloneDeep 行为 [英] Lodash .clone and .cloneDeep behaviors
问题描述
我尝试克隆具有嵌套对象的对象数组.
I try to clone an array of objects with nested objects.
类似于:
var data = [
{ id: 1, values: { a: 'a', b: 'b' } },
{ id: 2, values: { c: 'c', d: 'd' } }
];
_.克隆
使用 _.clone
方法和 isDeep<
true
处的/code> 参数:
_.Clone
With the _.clone
method and the isDeep
parameter at true
:
var clone = _.clone(data, true);
data[1].values.d = 'x';
console.log( _.isEqual(data, clone) ); // true, clone[1].values.d == 'x'
我期望 clone[1].values.d == 'd'
:
如果 isDeep 为真,嵌套对象也将被克隆,否则它们将通过引用分配.
If isDeep is true nested objects will also be cloned, otherwise they will be assigned by reference.
怎么了?
此外,当我尝试使用 _.cloneDeep
方法时,我收到一个错误:
In addition, when I try with the _.cloneDeep
method, I get an error:
var clone = _.cloneDeep(data);
// Uncaught TypeError: Object function u(n){return n instanceof u?n:new o(n)}
// has no method 'cloneDeep'
为什么会出现这个错误?
Why this error?
使用 $.extend
克隆没有引用原始对象如预期:
With $.extend
the clone has no reference to the original object as expected:
var clone = $.extend(true, {}, data);
console.log( _.isEqual(data, clone) ); // false, clone[1].values.d == 'd'
推荐答案
感谢 Gruff Bunny 和 Louis 的评论,我找到了问题的根源.
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
因为我也使用 Backbone.js,所以我加载了一个与 Backbone 和 Underscore 兼容的 Lodash 的特殊版本,它禁用了一些功能.在这个例子中:
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
- 普通构建:
_.isEqual(data, clone) === false
- 使用 Underscore 构建:
_.isEqual(data, clone) === true
我刚刚在我的 Backbone 应用程序中用普通版本替换了 Underscore 版本,该应用程序仍在工作.所以我现在可以使用具有预期行为的 Lodash .clone.
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: Underscore 构建 似乎不再存在.如果您在 2018 年阅读本文,您可能会对本文档感兴趣(Backbone 和 Lodash).
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
这篇关于Lodash .clone 和 .cloneDeep 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!