Table of Content
- Introduction
- Understanding and using structuredClone
- Conclusion
Introduction
Have you ever tried copying an object in Javascript using the spread operator (...), only to realize that changes to the original still affect the copy? It can be frustrating when you expect a copy independent from the original but end up having one linked to the original. This is a common issue when dealing with deep objects, and it can lead to unexpected bugs. Thankfully, Javascript has the structuredClone() method to solve this problem
Understanding and using structuredClone()
To start with, the structuredClone() method in Javascript is used to make deep copies of objects, including those with nested structures like arrays, objects and other complex data types.
You might be wondering: what exactly is a copy, and how many types of copying do we have in JavaScript? Well, we have the shallow and deep copies. While we know that structuredClone() creates the latter, using the spread operator creates the former.
A shallow copy copies only the top-level properties of an object, meaning nested objects or arrays are still referenced from the original. On the other hand, a deep copy duplicates everything, including nested structures, ensuring that the clone is fully independent of and from the original.
Let's see some examples of the Shallow and Deep copies in javascript
Shallow Copy Example
const person = { name: "John Doe", languages: [ "English", "German" ] }; const personClone = {...person}; // shallow copy // Modify the languages array in the cloned object personClone.languages.push("Spanish"); // Check the original and the cloned object console.log(person.languages); // Output: ["English", "German", "Spanish"] console.log(personClone.languages); // Output: ["English", "German", "Spanish"] console.log(person.languages === personClone.languages) // true // However, changing a primitive value won't affect the original personClone.name = "Jane Doe"; console.log(person.name); // Output: "John Doe" console.log(personClone.name); // Output: "Jane Doe" console.log(person.name === personClone.name) // false
From the code above, we can say the following:
- The name property is a primitive value, so changing it in the shallow copy(personClone.name = "Jane Doe";) does not affect the original (person.name)
- The languages array is non-primitive, so both the original(person) and the clone(personClone) share the same reference. Modifying the personClone array affects the original person array
Deep Copy Example
const person = { name: "John Doe", languages: [ "English", "German" ] }; // Create a deep copy using structuredClone const deepClonedPerson = structuredClone(person); // Modify the deep cloned object deepClonedPerson.languages.push("Spanish"); // Check if the original and the deep clone are equal console.log(person === deepClonedPerson); // Output: false console.log(person.languages) // ['English', 'German'] console.log(deepClonedPerson.languages) // ['English', 'German', 'Spanish'] console.log(person.languages === deepClonedPerson.languages); // Output: false // Check if the properties are equal console.log(person.name === deepClonedPerson.name); // Output: false // Changes in the deep cloned object don't affect the original deepClonedPerson.name = "Jane Doe"; console.log(person.name); // Output: "John Doe" console.log(deepClonedPerson.name); // Output: "Jane Doe"
From the code above, we can conclude the following:
- person === deepClonedPerson confirms that structuredClone() creates a new, independent object.
- person.languages === deepClonedPerson.languages shows that the nested array is also independently copied.
- Checking person.name === deepClonedPerson.name verifies that changes to the deep clone do not affect the original object.
- Values of languages demonstrate that modifications to the deep clone (deepClonedPerson) are not reflected in the original(person)
Conclusion
In this article, we explored how the structuredClone() method provides a reliable way to create deep copies of objects, ensuring that nested structures are fully independent of the original.
Thank you for reading through this article. If you found this article helpful, please like and share it with others who might benefit from learning about deep copying in Javascript
What are your thoughts on this topic? Have you encountered other techniques for copying objects in Javascript? Feel free to share your insights in the comments section below.
P.S. I'm currently looking for frontend developer opportunities. If you have any leads or are hiring, feel free to check out my resume or connect with me on LinkedIn. I'd love to hear from you!
以上是How to Use JavaScript&#s structuredClone() for Deep Object Cloning的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

记事本++7.3.1
好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具