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

วิธีตรวจสอบตัวแปร null, undefined, หรือ blank ใน JavaScript

จากผลลัพธ์ของโค้ดต่อไปนี้ สามารถทราบได้ว่าตัวแปรเป็น null หรือ undefined หากผลลัพธ์เป็น "false" หมายถึงตัวแปรเป็น null และ undefined

ที่นี่ตัวแปรให้ผลลัพธ์ "True":

<html> 
  <body> 
    <script> 
      var age = 10; 
      if (age) { 
        document.write("True"); 
      } else { 
        document.write("False"); 
      } 
    </script> 
  </body> 
</html>

ใช้ typeof เพื่อตรวจสอบว่าตัวแปรมีอยู่หรือไม่:

<html> 
  <body> 
    <script> 
      var age = 10; 
      if (typeof age !== 'undefined') { 
        document.write("True"); 
      } else { 
        document.write("False"); 
      } 
    </script> 
  </body> 
</html>

วิธีตรวจสอบครอบคลุม (Comprehensive Check)

function isEmpty(value) {
  // null, undefined
  if (value == null) return true;  // == null ครอบคลุมทั้ง null และ undefined
  
  // String ว่างหรือ whitespace
  if (typeof value === 'string' && value.trim() === '') return true;
  
  // Array ว่าง
  if (Array.isArray(value) && value.length === 0) return true;
  
  // Object ว่าง (ไม่มี own properties)
  if (typeof value === 'object' && Object.keys(value).length === 0) return true;
  
  return false;
}

// ตัวอย่างการใช้งาน
console.log(isEmpty(null));           // true
console.log(isEmpty(undefined));      // true
console.log(isEmpty(""));             // true
console.log(isEmpty("   "));          // true
console.log(isEmpty([]));             // true
console.log(isEmpty({}));             // true
console.log(isEmpty(0));              // false (0 เป็นค่าที่ valid)
console.log(isEmpty(false));          // false

สรุปการตรวจสอบ

กรณีโค้ด
undefined (ไม่ได้ประกาศ/ไม่ได้กำหนดค่า)typeof x === 'undefined'
nullx === null
null หรือ undefinedx == null
empty stringx === '' หรือ x.trim() === ''
empty arrayArray.isArray(x) && x.length === 0
empty objectObject.keys(x).length === 0