Destructuring

#HelloFrontend #HelloErmine #HelloWorld2021

Destructuring คืออะไร ?

คือ การหยิบค่าออกมาจาก array หรือ object แล้วนำไปใส่ในตัวแปรที่อยู่ข้างนอก

Object destructuring

สามารถหยิบค่าออกมาจาก key หรือ property ที่มีอยู่ใน object อยู่แล้วเท่านั้น (key ที่ไม่มีอยู่จะแสดงเป็น undefined)

let aCar = {
    fuel: 50,
    engine: 'V8',
    color: 'Intergalactic black',
    isStarted: false
};
 
let {fuel, engine, sussy} = aCar;

console.log(fuel);   // 50
console.log(engine); // V8
console.log(sussy);  // undefined (not in aCar)
console.log(color);  // ReferenceError: color is not defined

จากตัวอย่าง เราหยิบค่า fuel, engine และ sussy ออกมาจาก aCar (พร้อมกับการประกาศตัวแปร)

เราสามารถเปลี่ยนชื่อให้กับ key ที่เราหยิบออกมา หรือกำหนดค่าเริ่มต้นให้กับ key ที่ไม่มีอยู่ใน object ได้

...
let {fuel: gas, engine, sussy = 666} = aCar;
console.log(gas);    // 50
console.log(engine); // V8
console.log(sussy);  // 666

จากตัวอย่าง เราเปลี่ยน fuel เป็น gas และกำหนดค่าเริ่มต้นให้กับ sussy

Array destructuring

ค่าที่หยิบออกมาสามารถใช้ชื่ออะไรก็ได้ โดยจะได้ค่าเรียงตาม index

สามารถข้ามค่าที่ไม่ต้องการได้ด้วยการปล่อยชื่อตัวแปรว่างไว้ และสามารถกำหนดค่าเริ่มต้นให้กับตัวแปรที่เกิน index ได้ (ถ้าไม่กำหนดจะเป็น undefined)

let numnum = [4, 20, 666, 1337];
let [four, twenty, , leet, Kappa123, yes = true] = numnum;
 
console.log(four);     // 4
console.log(twenty);   // 20
// Skips 666
console.log(leet);     // 1337
console.log(Kappa123); // undefined
console.log(yes);      // true

จากตัวอย่าง เราข้ามค่า 666 และกำหนดค่าเริ่มต้นให้กับตัวแปร yes มีค่าเป็น true

แหล่งอ้างอิง 📑

Last updated

Was this helpful?