xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js structuredClone All In One

js structuredClone All In One

deep copy / deep clone

_.cloneDeep

JSON.parse & JSON.stringify

strucuredClone

image

https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy

structuredClone()

js 对象深复制的正确的、简洁的、优雅的写法 🚀

structuredClone(value)

structuredClone(value, options)

https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

image

polyfill

https://github.com/zloirock/core-js#structuredclone

image

bugs

image

image

image


Uncaught DOMException: Failed to execute 'structuredClone' on 'Window':  (v) => console.log(v)  could not be cloned.

Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': function (v) {console.log(v)} could not be cloned.

Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': Symbol(s) could not be cloned.


const origin = {
  num: 1,
  arr: [2012, 2023],
  // func: function (v) {console.log(v)},
  obj: {msg: 'bug'},
  date: new Date(`2012-01-01`),
  u: undefined,
  nil: null,
  nan: NaN,
  bool: true,
  str: 'string',
  // s: Symbol(`s`),
  bi: BigInt(10**32),
  set: new Set([1, 2, 3]),
  map: new Map([['a', 11], ['b', 22], ['c', 33]]),
  // reg: /^0+/g,
  reg: new RegExp(/^0+/g),
};


deepClone = structuredClone(origin);

image

demos

image

const deepObject = {
  title: "xgqfrms.xyz",
  // date: new Date(2023/01/01),
  // ❌ 2023/01/01
  // Thu Jan 01 1970 08:00:02 GMT+0800 (China Standard Time)
  date: new Date("2023/01/01"),
  // ✅ "2023/01/01"
  // Sun Jan 01 2023 00:00:00 GMT+0800 (China Standard Time)
  set: new Set(["xgqfrms", "webfullstack", "web", "es-next"]),
};

const objectDeepCopy = structuredClone(deepObject);

console.log(`objectDeepCopy =`, objectDeepCopy);
// objectDeepCopy = {title: 'xgqfrms.xyz', date: Sun Jan 01 2023 00:00:00 GMT+0800 (China Standard Time), set: Set(4)}date: Sun Jan 01 2023 00:00:00 GMT+0800 (China Standard Time) {}set: Set(4) {'xgqfrms', 'webfullstack', 'web', 'es-next'}title: "xgqfrms.xyz"[[Prototype]]: Object

objectDeepCopy.set.add(2023)
// Set(5) {'xgqfrms', 'webfullstack', 'web', 'es-next', 2023}

deepObject.set;
// Set(4) {'xgqfrms', 'webfullstack', 'web', 'es-next'}

image

Things that don't work with structured clone ⚠️

  1. Function objects cannot be duplicated by the structured clone algorithm;
    attempting to throws a DataCloneError exception.

  2. Cloning DOM nodes likewise throws a DataCloneError exception.

  3. Certain object properties are not preserved:

  • The lastIndex property of RegExp objects is not preserved.
  • Property descriptors, setters, getters, and similar metadata-like features are not duplicated.
    For example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default.
  • The prototype chain is not walked or duplicated.

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#things_that_dont_work_with_structured_clone

https://stackoverflow.com/questions/72632173/unable-to-use-structuredclone-on-value-of-ref-variable

const original = {
  title: "js structuredClone() vs JSON.parse(JSON.stringify())",
  obj: {author: "xgqfrms"},
  date: new Date(2023),
  set: new Set([1,2,3]),
  map: new Map([["k1", 1], ["k2", 2], ["k3", 3]]),
  arr: ["xgqfrms", "webfullstack"],
  func: (...args) => console.log(args),
}


const copyed = JSON.parse(JSON.stringify(original));
/*
{
  "title": "js structuredClone() vs JSON.parse(JSON.stringify())",
  "obj": {
    "author": "xgqfrms"
  },
  "date": "1970-01-01T00:00:02.023Z",
  "set": {},
  "map": {},
  "arr": [
    "xgqfrms",
    "webfullstack"
  ]
}
*/

const cloned = structuredClone(original);
// ❌  Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': (...args) => console.log(args) could not be cloned.

image

Transferable objects

ArrayBuffer

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects

refs

https://github.com/xgqfrms/learning-javascript-with-mdn/issues/6#issuecomment-1438466970

https://twitter.com/Steve8708/status/1615733451684188160

https://www.builder.io/blog/structured-clone



©xgqfrms 2012-2025

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(75)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2022-01-19 CSV 不支持导出 0.0 bug All In One
2021-01-19 VuePress config All In One
2021-01-19 auto deploy docs website
2020-01-19 APP 金刚区图标设计 & UI
2019-01-19 MacOS & dock 工具栏 & 外接显示器 & 主屏
点击右上角即可分享
微信分享提示