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

ฟังก์ชัน isNaN() ใน JavaScript

ฟังก์ชัน isNaN() ตรวจสอบว่าค่าที่ให้มาคือ NaN (Not-a-Number) หรือไม่ คืนค่า true หากเป็น NaN, false หากเป็นตัวเลขปกติ

ไวยากรณ์

isNaN(value)

ตัวอย่าง

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var result1 = parseFloat("Ef00A.D3");       document.write(isNaN(result1));       document.write('<br>');       var result2 = Math.log("welcome");       document.write(isNaN(result2));       document.write('<br>');       var result3 = Math.log(1254);       document.write(isNaN(result3));    </script> </body> </html>

ผลลัพธ์

true true false

คำอธิบาย:

  • parseFloat("Ef00A.D3") → NaN → true
  • Math.log("welcome") → NaN → true
  • Math.log(1254) → 7.134... (ตัวเลข) → false

⚠️ พฤติกรรมแปลกของ global isNaN():

isNaN("hello")    // true (แปลงเป็น NaN)
isNaN(undefined)  // true (แปลงเป็น NaN)
isNaN({})         // true (แปลงเป็น NaN)
isNaN("123")      // false (แปลงเป็น 123)

แนะนำ: Number.isNaN() (ES6+)

ค่าisNaN()Number.isNaN()
NaNtruetrue
"hello"truefalse
undefinedtruefalse
123falsefalse

วิธีตรวจสอบ NaN แบบเก่า (ก่อน ES6):

value !== value // เฉพาะ NaN ที่ไม่เท่ากับตัวเอง