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

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

ใน JavaScript ตรวจสอบตัวแปรว่าเป็นอาร์เรย์ได้ 3 วิธี

1) เมธอด isArray()

Array.isArray() ตรวจสอบตัวแปรที่ส่งเข้ามา คืนค่า true ถ้าเป็นอาร์เรย์ มิฉะนั้น false

รูปแบบ

Array.isArray(variableName)

ตัวอย่าง

<html> <body> <script type="text/javascript"> 
    arr = [1,2,3,4,5]; 
    str = "i love my india"; 
    document.write(Array.isArray(arr)); 
    document.write("<br>"); 
    document.write(Array.isArray(str)); 
</script> </body> </html>

ผลลัพธ์

true false

2) ตัวดำเนินการ instanceof

instanceof ทดสอบว่า prototype ของ constructor ปรากฏใน prototype chain ของออบเจ็กต์หรือไม่ ตรวจสอบว่า有 array prototype อยู่หรือไม่

รูปแบบ

variable instanceof Array

ตัวอย่าง

<html> <body> <script type="text/javascript"> 
    arr = [1,2,3,4,5]; 
    str = "i love my india"; 
    document.write(str instanceof Array); 
    document.write("<br>"); 
    document.write(arr instanceof Array); 
</script> </body> </html>

ผลลัพธ์

false true

3) ตรวจสอบ constructor property

คืนค่า true เมื่อตัวแปรตรงกับที่ระบุ (Array) มิฉะนั้น false

รูปแบบ

variable.constructor === Array

ตัวอย่าง

<html> <body> <script type="text/javascript"> 
    arr = [1,2,3,4,5]; 
    str = "i love my india"; 
    document.write(str.constructor === Array); 
    document.write("<br>"); 
    document.write(arr.constructor === Array); 
</script> </body> </html>

ผลลัพธ์

false true