DEV Community

hambalee
hambalee

Posted on

JavaScript Destructuring คืออะไร

Destructuring ในภาษา JavaScript เป็นการเขียนโค้ดแบบย่อสำหรับใช้กับ Array
(การใช้กับ Object ก็จะคล้าย ๆ กัน)

[a,b] = ["A","B] //เขียนบรรทัดเดียว เปรียบเสมือนว่า a = "A" b = "B" 
Enter fullscreen mode Exit fullscreen mode

อีกตัวอย่าง

const num = [1,2,3] [num1, num2] = num //จะได้ num1 = 1 ส่วน num2 = 2 
Enter fullscreen mode Exit fullscreen mode
const num = [1,2,3] [num1, ,num3] = num //จะได้ num1 = 1 ส่วน num3 = 3 //ค่า 2 จะไม่ถูกนำไปใช้เพราะ มีการเว้นไว้เพื่อข้ามไปตัวถัดไป 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)