如何通过引用将JavaScript对象复制到新变量? [英] How to copy JavaScript object to new variable NOT by reference?

查看:94
本文介绍了如何通过引用将JavaScript对象复制到新变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个快速的jsfiddle 这里,我将一个小的json对象传递给一个新变量并修改数据原始变量(不是新变量),但新变量的数据也会更新。这必须意味着json对象是通过引用传递的,对吗?

I wrote a quick jsfiddle here, where I pass a small json object to a new variable and modify the data from the original variable (not the new variable), but the new variable's data gets updated as well. This must mean that the json object was passed by reference, right?

这是我的快速代码:

var json_original = {one:'one', two:'two'}

var json_new = json_original;

console.log(json_original); //one, two
console.log(json_new); //one, two

json_original.one = 'two';
json_original.two = 'one';

console.log(json_original); //two, one
console.log(json_new); //two, one

有没有办法制作一个json对象的深层副本,以便修改原始变量不会修改新变量吗?

Is there a way to make a deep copy of a json object so that modifying the original variable won't modify the new variable?

推荐答案

如果你不使用,我发现以下内容有效jQuery,只对克隆简单对象感兴趣(参见评论)。

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

这篇关于如何通过引用将JavaScript对象复制到新变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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