js structuredClone All In One
js structuredClone All In One
deep copy / deep clone
_.cloneDeep
JSON.parse
& JSON.stringify
strucuredClone
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
polyfill
https://github.com/zloirock/core-js#structuredclone
bugs
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);
demos
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'}
Things that don't work
with structured clone ⚠️
-
Function
objects cannot be duplicated by the structured clone algorithm;
attempting to throws aDataCloneError
exception. -
Cloning
DOM
nodes likewise throws a DataCloneError exception. -
Certain object
properties
are not preserved:
- The
lastIndex
property ofRegExp
objects is not preserved.- Property descriptors, setters, getters, and similar
metadata-like
features are not duplicated.
For example, if an object is markedreadonly
with aproperty descriptor,
it will be read/write in theduplicate
, since that's the default.- The
prototype chain
is not walked or duplicated.
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.
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, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17060969.html
未经授权禁止转载,违者必究!