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

วิธีส่งออบเจ็กต์พารามิเตอร์เข้าไปในฟังก์ชันอย่างสง่างาม


โค้ดตัวอย่างการส่งออบเจ็กต์พารามิเตอร์เข้าไปในฟังก์ชัน ด้านล่าง

ตัวอย่าง

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .result,.sample {       font-size: 18px;       font-weight: 500;       color: rebeccapurple;    }    .sample {       color: red;    } </style> </head> <body> <h1>Passing an object of parameters into a function</h1> <div class="result"><br /></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to add 4 object values by passing them to a function</h3> <script>    let resEle = document.querySelector(".result");    let BtnEle = document.querySelector(".Btn");    function addNum({ a, b, c, d }) {       return a + b + c + d;    }    let obj = {       a: 22,       b: 33,       c: 7,       d: 9,    };    BtnEle.addEventListener("click", () => {       resEle.innerHTML = " The sum of the parameters = " + addNum(obj);    }); </script> </body> </html>

ผลลัพธ์

โค้ดด้านบนจะสร้างผลลัพธ์ดังนี้ −

วิธีส่งออบเจ็กต์พารามิเตอร์เข้าไปในฟังก์ชันอย่างสง่างาม

เมื่อคลิกปุ่ม ‘CLICK HERE’ −

วิธีส่งออบเจ็กต์พารามิเตอร์เข้าไปในฟังก์ชันอย่างสง่างาม