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

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

问题描述

我写了一个快速的 jsfiddle here,我将一个小的 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天全站免登陆