Native deep cloning(原生深克隆)
It's called "structured cloning", works experimentally in Node 11 and later, and hopefully will land in browsers.
(它被称为“结构化克隆”,可在Node 11及更高版本上进行实验性工作,并有望登陆浏览器。)
See this answer for more details.(有关更多详细信息,请参见此答案 。)
Fast cloning with data loss - JSON.parse/stringify(快速克隆而数据丢失-JSON.parse / stringify)
If you do not use Date
s, functions, undefined
, Infinity
, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:
(如果您不使用Date
,函数, undefined
, Infinity
,RegExps,Maps,Sets,Blobs,FileLists,ImageDatas,Sparse Arrays,Typed Arrays或对象中的其他复杂类型,则可以使用一种非常简单的方法来深度克隆对象:)
JSON.parse(JSON.stringify(object))
const a = { string: 'string', number: 123, bool: false, nul: null, date: new Date(), // stringified undef: undefined, // lost inf: Infinity, // forced to 'null' re: /.*/, // lost } console.log(a); console.log(typeof a.date); // Date object const clone = JSON.parse(JSON.stringify(a)); console.log(clone); console.log(typeof clone.date); // result of .toISOString()
See Corban's answer for benchmarks.
(有关基准,请参阅Corban的答案 。)
Reliable cloning using a library(使用库进行可靠的克隆)
Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects.
(由于克隆对象并非易事(复杂类型,循环引用,函数等),因此大多数主要库都提供了克隆对象的功能。)
Don't reinvent the wheel - if you're already using a library, check if it has an object cloning function.(不要重新发明轮子 -如果您已经在使用库,请检查它是否具有对象克隆功能。)
For example,(例如,)
ES6(ES6)
For completeness, note that ES6 offers two shallow copy mechanisms: Object.assign()
and the spread operator .
(为了完整起见,请注意ES6提供了两种浅表复制机制: Object.assign()
和spread操作符 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…