硬拷贝与浅拷贝javascript [英] Hard Copy vs Shallow copy javascript

查看:334
本文介绍了硬拷贝与浅拷贝javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个老问题,但我真的很好奇通过引用复制对象的性质作为javascript中的赋值。

This may be an old question but I'm really curious about the nature of copying objects by reference as an assignment in javascript.

这意味着如果

var a = {}; 
var b = a;
a.name = "Renato";
console.log(b); 
Object {name: "renato"}

我是javascript的新手这真的引起了我的注意,有一个浅拷贝作为对象赋值的默认值。我搜索了一下,为了创建一个硬拷贝,你必须创建一个mixin。我想知道为什么这被选为默认值,因为它的转换似乎非常含蓄。谢谢!

I'm kind of new to javascript and this really caught my attention to have a shallow copy as a default for Object assignment. I searched that in order to create a hard copy, you have to create a mixin. I was wondering why was this chosen as the default since it's transformation seems to be very implicit. Thanks!

推荐答案

对象和数组被视为对同一对象的引用。如果你想克隆这个对象,有几种方法可以做到这一点。

Objects and arrays are treated as references to the same object. If you want to clone the object, there are several ways to do this.

在以后的浏览器中,你可以这样做:

In later browsers, you can do:

var b = Object.assign({}, a);

如果你想去图书馆,lodash提供 _。clone (和 _。cloneDeep ):

If you want to go for a library, lodash provides _.clone (and _.cloneDeep):

var b = _.clone(a);

如果您不想执行这些方法中的任何一种,您只需枚举每个键和值并将它们分配给一个新对象。

If you don't want to do either of those methods, you can just enumerate through each key and value and assign them to a new object.

通常,当它们通过多个函数等时被视为引用是很有价值的。这不是原语的情况。喜欢数字和字符串,因为在大多数情况下这会让人觉得非常违反直觉。

Oftentimes it's valuable for them to be treated as references when passing through multiple functions, etc. This isn't the case for primitives like numbers and strings, because that would feel pretty counterintuitive in most cases.

这篇关于硬拷贝与浅拷贝javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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