Destructuring Assignment แยกค่าจาก Array/Object ให้ตัวแปรหลายตัวในบรรทัดเดียว
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Array Destructuring</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Array Destructuring in JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to destructure the array </h3>
<script>
let sampleEle = document.querySelector(".sample");
let resEle = document.querySelector(".result");
let arr = ["F", "G", 22, 44];
sampleEle.innerHTML = "arr = " + arr;
let a, b, c, d;
document.querySelector(".Btn").addEventListener("click", () => {
[a, b, c, d] = arr;
resEle.innerHTML = "After destructuring:<br>";
resEle.innerHTML += `a=${a} b=${b} c=${c} d=${d}`;
});
</script>
</body>
</html>
คำอธิบาย
Basic
const [a, b, c] = [1, 2, 3]; // a=1, b=2, c=3
Skip Values
const [a, , c] = [1, 2, 3]; // a=1, c=3 (ข้าม b)
Default Values
const [a = 10, b = 20] = [1]; // a=1, b=20
Rest Pattern
const [first, ...rest] = [1,2,3,4]; // first=1, rest=[2,3,4]
Swap Variables
[a, b] = [b, a]; // สลับค่าโดยไม่ต้อง Temp Variable
ผลลัพธ์
a=F b=G c=22 d=44