Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธี Clone ออบเจ็กต์ด้วย Spread Operator ใน JavaScript

การ clone ด้วย assignment operator (=) ทำให้ทั้งสองตัวแปรอ้างอิงออบเจ็กต์เดียวกัน (shallow reference) การเปลี่ยนแปลงตัวหนึ่งจะส่งผลต่ออีกตัว ES6 spread operator (...) สร้าง shallow copy แยกอ้างอิง

วิธีเดิม Assignment (Reference)

<html> <body> <script> 
    var org = {org1: "Serveneedy", org2: "Praveenlatha", org3: "Redcross"}; 
    document.write(JSON.stringify("without change org: " + JSON.stringify(org))); 
    var neworg = org; 
    org.org1 = "gatesfoundation"; 
    document.write("<br>"); 
    document.write(JSON.stringify("with change org: " + JSON.stringify(org))); 
    document.write("<br>"); 
    document.write(JSON.stringify("change also reflected in neworg: " + JSON.stringify(neworg))); 
</script> </body> </html>

ผลลัพธ์

ทั้ง org และ neworg เปลี่ยนไปด้วยกัน

วิธีใหม่ Spread Operator (Shallow Copy)

<html> <body> <script> 
    var org = {org1: "Serveneedy", org2: "Praveenlatha", org3: "Redcross"}; 
    document.write(JSON.stringify("without change org: " + JSON.stringify(org))); 
    var neworg = {...org}; 
    org.org1 = "gatesfoundation"; 
    document.write("<br>"); 
    document.write(JSON.stringify("with change org: " + JSON.stringify(org))); 
    document.write("<br>"); 
    document.write(JSON.stringify("change also reflected in neworg: " + JSON.stringify(neworg))); 
</script> </body> </html>

ผลลัพธ์

org เปลี่ยน แต่ neworg คงค่าเดิม