การแปลง data type จากหนึ่งเป็นอีกอย่างหนึ่ง เรียกว่า type casting บางครั้งต้องแปลง data type ของค่าหนึ่งเป็นอีกประเภท ภายใต้บางสถานการณ์ JavaScript จะทำ automatic type conversion
ประเภทของการแปลง
Automatic Type Conversion
JavaScript คาดหวัง boolean ใน conditional expression จะแปลงค่าใน parentheses เป็น boolean ชั่วคราวเพื่อ evaluate if expression
if (val) { console.log( 'yes, val exists' ); }ค่าต่อไป evaluate เป็น false: 0, -0, '' (empty string), NaN, undefined, null ค่าอื่นๆ ล้วนเป็น true แม้ empty arrays และ objects
Type conversion ยังเกิดเมื่อเปรียบเทียบด้วย equal (==) และ not equal (!=) operators เปรียบเทียบ number 125 กับ string '125' ด้วย == จะได้ true
console.log( 125 == '125' );
Type conversion ไม่เกิดเมื่อใช้ identical (===) และ not identical (!==) operators
Explicit Type Conversion
parseInt และ parseFloat
parseInt แปลง argument แรกเป็น string, parse แล้วคืน integer หรือ NaN
parseFloat() parse argument (แปลงเป็น string ก่อนถ้าจำเป็น) คืน floating point number
toString
toString() คืน string representing the object พยายามแปลง object เป็น string
ตัวอย่าง
let a = 1.015 console.log(a) console.log(typeof a) console.log(a.toString()) console.log(typeof a.toString())
ผลลัพธ์
1.015 number 1.015 string