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

วิธีบวกสตริงและตัวเลขโดยไม่ให้ต่อสตริงใน JavaScript

การบวกสตริงกับตัวเลขโดยตรงจะเกิด concatenation (ต่อสตริง) ต้องแปลงสตริงเป็นตัวเลขก่อน ใช้ Unary + หรือ parseInt()

ตัวอย่างที่ 1: ต่อสตริง (ผิด)

<html> <body> <script> 
    const string = "100"; 
    const number = 5; 
    document.write(string + number); 
</script> </body> </html>

ผลลัพธ์

1005

ตัวอย่างที่ 2: ใช้ Unary + แปลงก่อนบวก

<html> <body> <script> 
    const string = "100"; 
    const number = 5; 
    document.write(+string + number); 
</script> </body> </html>

ผลลัพธ์

105

ตัวอย่างที่ 3: ใช้ parseInt()

<html> <body> <script> 
    const string = "100"; 
    const number = 5; 
    document.write(parseInt(string) + number); 
</script> </body> </html>

ผลลัพธ์

105