หลายๆคนคงเคยเจอปัญหา กับ การรับค่าจาก input เป็นตัวเลขมา เพื่อจะนำมาคำนวนกัน เช่น รับ “1″ และ ”2″ มาและอยากจะนำมาบวกกัน แต่ทำไมผลลัพท์มันจึง ออกมาเป็น ”12″ หวา แต่ถ้าบางคนยังมองไม่เห้น ภาพ หรือ งงๆ อยู่ลองดูตัวอย่าง ต่อไปนี้แล้วกันนะ ครับ (อธิบายด้วย code ละ )
คำถาม คือ
Step (1) จะต่อ (string) “1″, “2″, “3″ ให้เป็น “123″ ได้อย่างไร
Step (2) จะเปลี่ยน (string) “123″ ให้เป็น (int)123 ได้อย่างไร
Step (3) 123 + 100 = 223
Step (4) จะเปลี่ยน (int) 223 เป็น (string) “223″ ได้อย่างไร
keyword ของการแก้ปัญหานี้ คือ method parseInt () และ toString () และ ถ้าหากคุณอยากรู้
ว่า ตัวแปรนั้นมี type เป็นชนิดไหน ลองใช้ typeof ดูนะครับ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
<script type= "text/javascript" >
function printWithType(val) {
document.write( '<pre>' );
document.write(val);
document.write( ' ' );
document.writeln( typeof val);
document.write( '</pre>' );
}
var a = "1" , b = "2" , c = "3" , result;
result = a + b + c;
printWithType(result);
result = a.toString() + b.toString() + c.toString();
printWithType(result);
result = parseInt(result,10);
printWithType(result);
result = result + 100;
printWithType(result);
result = result.toString();
printWithType(result);
result = result + "" ;
printWithType(result);
</script>
|