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

Optional Arguments (อาร์กิวเมนต์ตัวเลือก) ในฟังก์ชัน JavaScript

ใน JavaScript สามารถทำให้พารามิเตอร์เป็น ตัวเลือก (optional) ได้โดยใช้ Default Parameters (ES6) กำหนดค่าเริ่มต้นไว้ในหัวฟังก์ชัน

ตัวอย่าง

<html>
  <body>
    <script>
      // default inc = 1
      function inc(val1, inc = 1) {
        return val1 + inc;
      }

      document.write(inc(10, 10)); // 20
      document.write("<br>");
      document.write(inc(10));     // 11 (ใช้ค่าเริ่มต้น)
    </script>
  </body>
</html>

วิธีเก่า (Pre-ES6)

function inc(val1, inc) {
  inc = (inc !== undefined) ? inc : 1; // หรือ inc = inc || 1 (แต่ 0 จะถูกแทนด้วย 1)
  return val1 + inc;
}

รายละเอียดเพิ่มเติม

  • ค่าเริ่มต้นสามารถเป็นนิพจน์ (expression) ได้: function foo(x = Date.now())
  • พารามิเตอร์ก่อนหน้าอ้างอิงได้: function foo(a = 1, b = a * 2)
  • ทำงานกับ Destructuring: function foo({x = 1, y = 2} = {})
  • ส่ง undefined จะใช้ค่าเริ่มต้น, ส่ง null จะเป็น null (ไม่ใช้ค่าเริ่มต้น)

ตัวอย่างขั้นสูง

// Required parameter (บังคับส่ง) - ใช้ฟังก์ชันช่วย
function required() { throw new Error("Missing parameter"); }
function foo(must = required(), optional = "default") { ... }

// Destructuring with defaults
function connect({ host = "localhost", port = 3000, secure = false } = {}) {
  // ใช้ host, port, secure ได้เลย
}
connect(); // ใช้ค่าเริ่มต้นทั้งหมด
connect({ port: 8080 }); // host="localhost", port=8080, secure=false

แนะนำ: ใช้ Default Parameters (ES6) เป็นหลัก วิธีเก่าใช้เฉพาะรองรับเบราว์เซอร์เก่ามาก