Có 5 cách để chuyển giá trị thành chuỗi (string):
- Nối chuỗi rỗng (
value + '') - Template strings (
\`${value}\`) JSON.stringify()toString()String()
Ví dụ
Tất cả phương pháp trên được dùng để chuyển giá trị thành chuỗi, kết quả hiển thị như output.
<html> <body> <script> const value = 123; document.write((value + '') +" "+typeof (value + '')); document.write("</br>"); document.write((`${value}`) +" "+typeof (`${value}`)); document.write("</br>"); document.write((JSON.stringify(value)) +" "+typeof (JSON.stringify(value))); document.write("</br>"); document.write((value.toString()) +" "+typeof (value.toString())); document.write("</br>"); document.write((String(value)) +" "+typeof(String(value))); </script> </body> </html>
Kết quả
123 string 123 string 123 string 123 string 123 string
So sánh:
value + '': Nhanh, phổ biến, nhưng không xử lý null/undefined an toàn\`${value}\`: ES6, dễ đọc, hỗ trợ interpolationJSON.stringify(): Dùng cho object/array, escape ký tự đặc biệttoString(): Method của object, lỗi nếu value là null/undefinedString(): Hàm global, an toàn với null/undefined (trả về "null"/"undefined")