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

วิธีตรวจสอบว่าตัวแปรเป็น Boolean ใน JavaScript

ใช้ตัวดำเนินการ typeof ตรวจสอบชนิดข้อมูลของตัวแปร

ตัวอย่าง

<html>
  <head>
    <title>JavaScript Boolean</title>
  </head>
  <body>
    <script>
      var answer = true;
      if (typeof answer === "boolean") {
        alert("Boolean");
      } else {
        alert("Not a Boolean");
      }
    </script>
  </body>
</html>

ตาราง typeof results

Valuetypeof
true / false"boolean"
new Boolean(true)"object"
0, 1, -1"number"
"true", "false""string"
null"object" (bug แห่งนี้)
undefined"undefined"

ฟังก์ชันตรวจสอบแบบครบถ้วน

function isBoolean(value) {
  return typeof value === 'boolean' || value instanceof Boolean;
}

console.log(isBoolean(true));           // true
console.log(isBoolean(false));          // true
console.log(isBoolean(new Boolean()));  // true
console.log(isBoolean(1));              // false
console.log(isBoolean("true"));         // false

หมายเหตุ: new Boolean(false) เป็น object ไม่ใช่ primitive typeof คืน "object" แต่ในบริบท boolean context จะเป็น falsy