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

ความสำคัญของออเปอเรเตอร์ '+' ในการแปลงชนิดข้อมูลใน JavaScript

ออเปอเรเตอร์ + ใช้ได้หลายอย่าง: บวกเลข ต่อสตริง และ แปลงชนิดข้อมูล (type conversion) โดยเฉพาะการแปลงสตริงเป็นตัวเลข

ตัวอย่าง แปลงสตริงเป็นตัวเลข

<html> <body> <script> 
    var num = "23"; 
    int = +num; 
    document.write(int); 
    document.write("<br>"); 
    document.write(typeof int); 
</script> </body> </html>

ผลลัพธ์

23 number

ยังแปลง boolean เป็นตัวเลขได้: true → 1, false → 0

ตัวอย่าง แปลง Boolean

<html> <body> <script> 
    document.write(+true); 
    document.write("<br>"); 
    document.write(+false); 
</script> </body> </html>

ผลลัพธ์

1 0