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

Undefined ใน JavaScript

คุณสมบัติ undefined ของ 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;
    }
    .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
    }
  </style>
</head>
<body>
  <h1>คุณสมบัติ undefined ของ JavaScript</h1>
  <div class="sample"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อทราบว่าตัวแปร age ถูกกำหนดหรือยัง</h3>
  <script>
    let sampleEle = document.querySelector(".sample");
    let age;
    document.querySelector(".Btn").addEventListener("click", () => {
      if (age === undefined) {
        sampleEle.innerHTML = "ตัวแปร age ยังไม่ได้ถูกกำหนดหรือไม่มีค่าให้";
      } else {
        sampleEle.innerHTML = "ตัวแปร age ถูกกำหนดและค่าคือ = " + age;
      }
    });
  </script>
</body>
</html>

ผลลัพธ์

Undefined ใน JavaScript

เมื่อคลิกปุ่ม ‘คลิกที่นี่’:

Undefined ใน JavaScript