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

JavaScript TypeError: สาเหตุและวิธีแก้ไข

ใน JavaScript TypeError คืออ็อบเจ็กต์แทนข้อผิดพลาดจากการดำเนินการที่ไม่สามารถทำได้ ปกติเพราะค่าใน operation ไม่ใช่ type ที่คาดหวัง

ชนิดข้อมูล 9 ชนิดใน JavaScript (ECMAScript)

  1. undefined: ค่าที่กำหนดให้ตัวแปรที่ประกาศแต่ยังไม่กำหนดค่า
  2. Boolean: true หรือ false
  3. Number: ตัวเลข
  4. String: ลำดับตัวอักษรใน backticks, single/double quotes
  5. BigInt: ตัวเลขขนาดใหญ่
  6. Symbol: unique identifier จาก Symbol()
  7. Object: structural type (array, object, map, set, ทุกอย่างที่ new สร้าง)
  8. Function: โครงสร้างโค้ดที่เรียกใช้ได้
  9. null: ค่า intentional แทน object/address ที่ไม่มีอยู่

ใช้ typeof operator ตรวจสอบ type ได้

TypeError พบบ่อยและวิธีแก้

1. พยายามเปลี่ยนค่าที่เปลี่ยนไม่ได้ (const)

const a = 5;
a = "5"; // TypeError: Assignment to constant variable

แก้: ใช้ชื่อตัวแปรใหม่ const b = "5"

2. ใช้ค่าในวิธีที่ไม่เหมาะสม

function Cat() {}
let garfield = new Cat();
Cat instanceof garfield; // TypeError: Right-hand side of 'instanceof' is not callable

แก้: สลับลำดับ garfield instanceof Cat

3. Argument ไม่เข้ากับ type ที่ฟังก์ชันคาดหวัง

function readingErrorsAreImportant(a){
  if(a.length === 5){ return "equals five"; }
  else if(a.length > 5) { return "Greater than five"; }
  else { return "Less than five"; }
}
console.log(readingErrorsAreImportant(null)); // TypeError: Cannot read property 'length' of null

แก้: ส่งค่าที่มี property length เช่น string หรือ array readingErrorsAreImportant(10) (แต่ 10 ไม่มี length) ควรส่ง "hello" หรือ [1,2,3,4,5]

สรุป

เข้าใจว่าทำไมโค้ดโยน TypeError จะช่วย debug ได้ ใช้ typeof ตรวจสอบ type เมื่อไม่แน่ใจ