gpt4 book ai didi

javascript - 结构化克隆算法与深拷贝有何不同

转载 作者:数据小太阳 更新时间:2023-10-29 05:37:45 25 4
gpt4 key购买 nike

有一个 MDN article声明:

The structured clone algorithm is a new algorithm defined by the HTML5 specification for serializing complex JavaScript objects. It's more capable than JSON

所以,我相信这意味着它比以这种方式克隆的能力更强:

JSON.parse(JSON.stringify(obj))

this thread 中建议. JSON 方式有很多缺点,例如不支持循环引用、丢弃 JSON 规范不支持的所有内容(如函数)以及将 Date 对象表示为字符串。

然后我想到结构化克隆算法是很多库实现的深拷贝算法。但是,它在同一页上列出了以下文字:

If you want a deep copy of an object (that is, a recursive copy of all nested properties, walking the prototype chain), you must use another approach. The following is a possible example.

所以现在我很困惑,不知道什么是结构化算法,也不知道它与深拷贝有何不同。有什么帮助吗?我不想阅读规范,也许某些库实现了它,所以我可以阅读它们的源代码。

最佳答案

Structued Clone Algorithm 是深度复制 JavaScript 对象 的方法之一。由于此 API 未直接公开,因此我们可以通过其他方式使用它。

如果我们有 JSON.parse 和 JSON.stringify 为什么还要使用它?

Because JSON.parse(JSON.stringify(obj)) has some limitations like you have mentioned, which are, they do not serialize the circular object or things like Map, Set, Date, RegEx etc.

所以,这就是这个 api(Structure clone)发挥作用的地方。

如何使用?

Since this api(Structured Cloning) is not directly exposed but it is used by some other apis. So we can use those other apis in order to use Structured Cloning.

这些 api 是:

  1. history.pushState
  2. 消息 channel
  3. 通知

要查看这些 api 的示例和比较,我强烈推荐 Surma blogpost .


更新

因此,最终 Structured Clone api 以函数名 structuredClone() 直接暴露在某些浏览器中(see supported versions and coverage)。

如何使用?

带有日期对象的例子:

const a = { x: 20, date: new Date() };
const b = structuredClone(a); // { x: 20, date: <date object> }

注意:使用 JSON.stringify,日期对象将使用 Date.prototype.toJSON 序列化

圆形对象示例:

const a = { x: 20, date: new Date() };
a.c = a;
const b = structuredClone(a); // { x: 20, date: <date object>, c: <circular ref> }

注意:使用 JSON.stringify 会抛出 TypeError

关于javascript - 结构化克隆算法与深拷贝有何不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com