在 JavaScript 中深度克隆对象的最有效方法是什么?
技术问答
387 人阅读
|
0 人回复
|
2023-09-11
|
我做过类似obj = JSON.parse(JSON.stringify(o));但是质疑效率。/ t, d* n' {9 J( [3 e6 Y4 E: E
我还看到了各种缺陷的递归复制函数。* S0 s7 R' [+ t6 g& f* r
我很惊讶没有标准化的解决方案。) P7 A. [& M: ?" p
+ `) d2 c: ` I g. Z# {3 R/ C 解决方案:
8 K& U0 V% m6 {: \: E3 ]3 n Native deep cloning现在有个名字structured cloning的 JS 标准,它在 Node 11 及更高版本进行实验性工作,将登录浏览器,并有适合现有系统的 polyfill。' d w, O6 K1 i5 d* `* m
structuredClone(value)
% A$ k6 r8 Z; u 如有必要,先加载 polyfill:, `8 ]6 {8 ]: U, U! r- G" b; e
import structuredClone from '@ungap/structured-clone';# @" `' T2 T p( T& U
较旧的答案数据丢失的快速克隆 - JSON.parse/stringify如果不使用DateS,功能,undefined,Infinity,文件列表,正则表达式,地图,集合,斑点,ImageDatas,在稀疏数组、类型化数组或其他复杂类型的对象中,衬垫深克隆的简单对象是:
8 K H; T B. e! ~5 y, W$ GJSON.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 objectconst clone = JSON.parse(JSON.stringify(a));console.log(clone);console.log(typeof clone.date); // result of .toISOString()
, V1 L* W7 R x A# m) _! A 使用library可靠克隆由于克隆对象不容易(复杂类型、循环引用、函数等),大多数主要都提供了克隆对象的函数。不要重新发明轮子- 如果您已经在使用库,请检查它是否具有对象克隆功能。
0 _8 b/ J; j4 rlodash - cloneDeep; 可以通过lodash.clonedeep单独导入模块。如果您还没有使用提供深度克隆功能的库,它可能是您的最佳选择, w' P& i& u! A
AngularJS - angular.copy
V8 H6 T9 D! y KjQuery - jQuery.extend(true,{ },oldObject); .clone()只克隆 DOM 元素
L/ l/ ~5 Y; B9 l4 ajust library - just-clone; 零依赖 npm 模块库的一部分。适用于各种场合的无罪公用事业。ES6(shallow copy)请注意 起见,请注意 ES6 提供了两种浅拷贝机制:Object.assign() 和 spread syntax. 。它将所有可枚举属性的值从一个对象复制到另一个对象。6 }9 `6 h9 p3 P
var A1 = {a: "2"};var A2 = Object.assign({},A1);var A3 = {...A / Spread Syntax3 i' V; S( _! J$ W7 p, ?# O! w
|
|
|
|
|
|