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

วิธีแปลงค่าเป็น Boolean ใน JavaScript

มี 3 วิธี: 1) new Boolean() 2) Boolean() 3) !! (Double NOT) ES6

ใช้ Boolean keyword

<html> <body> <script> 
    const isTrue = 'Golden State Warriors'; 
    document.write(new Boolean(isTrue)); 
    document.write("<br>"); 
    document.write(Boolean(isTrue)); 
</script> </body> </html>

ผลลัพธ์

true true

ใช้ !! (Double NOT)

<html> <body> <script> 
    const isTrue = 'Golden State Warriors'; 
    document.write(!!isTrue); 
</script> </body> </html>

ผลลัพธ์

true

!! แปลงค่าให้เป็น boolean จริง (truthy/falsy) สั้นที่สุดและใช้กันทั่วไป