Ecma6,Object.assign不做深层复制 [英] Ecma6, Object.assign doesn't do a deep copy

查看:97
本文介绍了Ecma6,Object.assign不做深层复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dst = { "a" : 1}
src = { "edf" : {"zyx" : "right"}}
Object.assign(dst, src)
src.edf.zyx = "wrong"
console.log(dst["edf"]["zyx"])

我希望看到'right'作为输出,但它会显示'wrong'.

I expect to see 'right' as the output but it prints 'wrong'.

这意味着,Object.assign尚未从源到目标对复杂对象进行深层复制.我该如何进行深度复制?

It means, Object.assign has not done a deep copy of complex objects from source to destination. How can i do deep copy?

注意:我知道lodash.deepClone,但是我试图避免使用外部框架

Note: i am aware of lodash.deepClone, but i am trying to avoid outside frameworks

推荐答案

首先,我想告诉您这不是防弹解决方案(对于日期对象).如果您希望正确"作为答案,请采用以下解决方案:

First I want to tell you that it's not bulletproof solution (in case of date object). If you want "right" as answer, here is your solution:

var dst,src = { "edf" : {"zyx" : "right"} };
dst = JSON.parse(JSON.stringify(src));
dst["a"] = 1;
src.edf.zyx = "wrong";
console.log(src, dst);

因此,请阅读这些链接以更好地了解深层复制

So please read these links to understand deep copy better

克隆JavaScript对象的最优雅的方法

将JavaScript对象复制到新变量NOT通过引用?

这篇关于Ecma6,Object.assign不做深层复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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