How to copy JavaScript object to new variable NOT by reference?
This question already has an answer here:
我发现如果你不使用jQuery,只对克隆简单对象感兴趣,请参阅以下内容(请参阅注释)。
JSON.parse(JSON.stringify(json_original));
Your only option is to somehow clone the object.
See this stackoverflow question on how you can achieve this.
For simple JSON objects, the simplest way would be:
var newObject = JSON.parse(JSON.stringify(oldObject));
if you use jQuery, you can use:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:
In ES6 or TypeScript (2.1+):
var shallowCopy = { ...oldObject };
var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };
Note that if extraProp
is also a property on oldObject, its value will not be used because the extraProp : "abc"
is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.
上一篇: 克隆对象无参考javascript