如何使用下划线克隆对象数组? [英] How do you clone an array of objects using underscore?

查看:39
本文介绍了如何使用下划线克隆对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/env node
var _ = require('underscore');
var a = [{f: 1}, {f:5}, {f:10}];
var b = _.clone(a);
b[1].f = 55;
console.log(JSON.stringify(a));

结果是:

[{"f":1},{"f":55},{"f":10}]

克隆似乎无法正常工作!因此,我进行RTFM,然后看到以下内容:

Clone does not appear to be working! So I RTFM, and see this:

http://underscorejs.org/#clone

创建对象的浅表副本.任何嵌套对象或数组都将通过引用复制,而不是重复.

Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

所以 _.clone 几乎没有用.有没有一种方法可以实际复制对象数组?

So _.clone is pretty useless. Is there a way to actually copy the array of objects?

推荐答案

嗯,有个窍门!如果clone不克隆"嵌套对象,则可以通过显式克隆map调用中的每个对象来强制它!像这样:

Well, there is a trick! If clone does not "clone" nested objects, you can force it to by explicitly cloning each object inside a map call! Like this:

#!/usr/bin/env node
var _ = require('underscore');
var a = [{f: 1}, {f:5}, {f:10}];
var b = _.map(a, _.clone);       // <----
b[1].f = 55;
console.log(JSON.stringify(a));

打印:

[{"f":1},{"f":5},{"f":10}]

是的! a 不变!我现在可以按自己的喜好编辑 b

Yay! a is unchanged! I can now edit b to my liking!

这篇关于如何使用下划线克隆对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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