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

typeof Operator ใน JavaScript: ตรวจสอบชนิดข้อมูล (Data Type)

typeof Operator ใน JavaScript คืออะไร?

typeof เป็น Unary Operator (ตัวดำเนินการตัวเดียว) วางก่อน Operand เพื่อคืนค่า String ที่บ่งชี้ชนิดข้อมูล (Data Type) ของ Operand นั้น

ตารางค่าที่ typeof คืนค่า

ชนิดข้อมูล (Type)ค่าที่ typeof คืน (String)
Number"number"
String"string"
Boolean"boolean"
Object (รวม Array, Null, Date, Regexp, etc.)"object"
Function"function"
Undefined"undefined"
Symbol (ES6+)"symbol"
BigInt (ES2020+)"bigint"

จุดสำคัญ: Null เป็น "object"

typeof null === "object"; // true

นี่คือ Bug ที่รู้จักมาตั้งแต่ JavaScript แรก แต่ไม่ได้แก้เพื่อ Backward Compatibility ต้องตรวจสอบ Null แยกต่างหาก: val === null

ตัวอย่างโค้ด

<html>
  <body>
    <script>
      var a = 10;
      var b = "String";
      var linebreak = "<br />";

      result = (typeof b == "string" ? "B is String" : "B is Numeric");
      document.write("Result => ");
      document.write(result);
      document.write(linebreak);

      result = (typeof a == "string" ? "A is String" : "A is Numeric");
      document.write("Result => ");
      document.write(result);
      document.write(linebreak);
    </script>
  </body>
</html>

ตัวอย่างเพิ่มเติม

console.log(typeof 42);              // "number"
console.log(typeof "hello");         // "string"
console.log(typeof true);            // "boolean"
console.log(typeof undefined);       // "undefined"
console.log(typeof {});              // "object"
console.log(typeof []);              // "object" (Array เป็น Object)
console.log(typeof null);            // "object" (Bug)
console.log(typeof function(){});    // "function"
console.log(typeof Symbol());        // "symbol"
console.log(typeof 9007199254740991n); // "bigint"

// ตรวจสอบ Array จริง
Array.isArray([]);     // true
Array.isArray({});     // false

// ตรวจสอบ Null
val === null;          // true เฉพาะ null

การใช้งานจริง (Use Cases)

  • Validation: if (typeof input !== "string") throw Error
  • Conditional Logic: typeof callback === "function" && callback()
  • Debugging: console.log(typeof variable)
  • Feature Detection: typeof window !== "undefined" (Browser vs Node.js)

สรุป

typeof ใช้ตรวจสอบ Data Type แบบ Runtime คืนค่า String 7-9 ค่า (ขึ้นกับ ES Version) ข้อระวัง: typeof null === "object" และ typeof [] === "object" ต้องใช้ Array.isArray() และ val === null แทน