时间:2021-07-01 10:21:17 帮助过:36人阅读
object.assign
方法仅执行浅度克隆。这意味着嵌套属性仍然通过引用克隆。注,浅度克隆:简单类型为值传递,对象类型是引用的传递。深度克隆:所有元素或属性完全复制,与原对象完全脱离,也就是说所有对于新对象的修改都不会反映到原对象中。
克隆JavaScript对象有几种方法,如下:
示例1:一种方法是遍历源对象的属性,并将所有属性逐个复制到目标对象。它很简单,但不常使用。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > js克隆对象 </h1> <p id="demo2">sourceObject = {a:1, b:2, c:3};</p> <button onClick="fun()">click </button> <p id="demo"></p> <script> function fun(){ const sourceObject = {a:1, b:2, c:3}; let tO = {}; for (let prop in sourceObject) { if (sourceObject.hasOwnProperty(prop)) { tO[prop] = sourceObject[prop]; } } document.getElementById("demo").innerHTML = "targetObject a = "+tO.a+", b = " + tO.b+", c = "+tO.c; } </script> </body> </html>
输出:
点击按钮前
点击按钮后
示例2:此示例使用JSON。使用此方法,源对象必须是JSON安全的。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > js克隆对象 </h1> <p id="demo2">sourceObject = {a:1, b:2, c:3};</p> <button onClick="fun()">click </button> <p id="demo"></p> <script> function fun(){ const sourceObject = {a:1, b:2, c:3}; let tO = {}; tO = JSON.parse(JSON.stringify(sourceObject)); document.getElementById("demo").innerHTML = "targetObject a = "+tO.a+", b = " + tO.b+", c = "+tO.c; } </script> </body> </html>
示例3:此方法使用Object.assign
方法。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > js克隆对象 </h1> <p id="demo2">sourceObject = {a:1, b:2, c:3};</p> <button onClick="fun()">click </button> <p id="demo"></p> <script> function fun(){ const sourceObject = {a:1, b:2, c:3}; let tO = {}; tO = Object.assign({}, sourceObject); document.getElementById("demo").innerHTML = "targetObject a = "+tO.a+", b = " + tO.b+", c = "+tO.c; } </script> </body> </html>
相关推荐:《javascript教程》
本篇文章就是关于javascript克隆对象的方法介绍,希望对需要的朋友有所帮助!
以上就是JavaScript如何实现克隆对象?的详细内容,更多请关注Gxl网其它相关文章!