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

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

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-2021

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

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


posted @ 2023-01-19 16:20  xgqfrms  阅读(57)  评论(2编辑  收藏  举报