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
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, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17060969.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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 工具栏 & 外接显示器 & 主屏