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

ฟังก์ชัน Boolean ใน JavaScript

Boolean Function

ขณะพัฒนา Developer อาจเจอสถานการณ์ Yes/No ณ จุดนั้นใช้ฟังก์ชัน Boolean() ได้ ผลลัพธ์มีแค่ True หรือ False มาดูรายละเอียดกัน

Syntax

Boolean(exp);

รับ Expression ตรวจสอบและแสดง True หรือ False ตามความถูกต้องของ Expression

ตัวอย่างที่ 1

ในตัวอย่างนี้ ตรวจสอบค่าต่างๆ ว่าเป็น True หรือไม่ด้วย Boolean() หากค่าใดมี ค่าจริง (Legitimate) จะได้ True มิฉะนั้น False

<html> <body> <p id = "boolean"></p> <script> var a = 0;                         document.write(Boolean(a));          ///  displays false var b = 1; document.write(Boolean(b));          /// displays true       var x = Boolean(100); var y = Boolean("Hello"); var z = Boolean('false'); document.getElementById("boolean").innerHTML = "45 is " + x + "</br>" + "a string 'Hello' is " + y + "</br>" + "a false value is " + z ; </script> </body> </html>

ผลลัพธ์

45 is true a string 'Hello' is true a false value is true false true

ตัวอย่างที่ 2

ในตัวอย่างนี้ ส่ง Expression เข้า Boolean() ตรวจสอบความถูกต้อง หาก Expression ถูกต้อง (Legitimate) จะได้ True มิฉะนั้น False

<html> <body> <script> document.write(Boolean(10 > 5)); document.write("</br>"); document.write(Boolean(1 > 4)); </script> </body> </html>

ผลลัพธ์

true false