Cloning คือ copy อาร์เรย์ไปอีกอาร์เรย์หนึ่ง แบบเก่าใช้ slice() แต่ ES6 มี spread operator (...) ทำให้ง่ายขึ้น
Clone ด้วย slice()
ตัวอย่าง
slice() ตัดอาร์เรย์จาก index หนึ่งไปอีก index ไม่ระบุ index = ตัดทั้งอาร์เรย์ copy ไปอีกตัวด้วย assignment (=)
<html> <body>
<script>
const games = ['cricket', 'hockey', 'football', 'kabaddi'];
const clonegames = games.slice();
document.write(clonegames);
</script>
</body> </html>
ผลลัพธ์
cricket,hockey,football,kabaddi
Clone ด้วย Spread Operator
ES6 นำเสนอ spread operator ใช้ clone ได้ง่าย
ตัวอย่าง
<html> <body>
<script>
const games = ['cricket', 'hockey', 'football', 'kabaddi'];
const clonegames = [...games];
document.write(clonegames);
</script>
</body> </html>
ผลลัพธ์
cricket,hockey,football,kabaddi