Lodash .clone和.cloneDeep行为 [英] Lodash .clone and .cloneDeep behaviors

查看:392
本文介绍了Lodash .clone和.cloneDeep行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用嵌套对象克隆一个对象数组。

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' } }
];



_。克隆



使用< a href =http://lodash.com/docs#clone =noreferrer> _。clone 方法和 isDeep 参数 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'

为什么会出现此错误?

使用 $ .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

    • with the Normal build: _.isEqual(data, clone) === false
    • with the Underscore build: _.isEqual(data, clone) === true
    • 我刚用Backbone应用程序中的Normal build替换了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.

      编辑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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆