Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tầm quan trọng của template strings (chuỗi mẫu) ES6 trong JavaScript


Template strings ES6 là cách mới kết hợp chuỗi. Đã có join(), concat() nhưng template strings tinh tế (sophisticated) nhất vì: dễ đọc, không cần backslash escape quote, không còn toán tử + rối rắm.

Dùng concat() và join()

Ví dụ

Dùng join() và concat() kết hợp chuỗi. Mã trông rất rối.

<html> <body> <script> 
    const platform = 'Tutorix'; 
    const joinMethod = ['The', 'best', 'e-learning', 'platform', 'is', platform].join(' '); 
    document.write(joinMethod); 
    document.write("</br>"); 
    const concatMethod = " ".concat('The ', 'best ', 'e-learning ', 'platform ', 'is ', platform); 
    document.write(concatMethod); 
</script> </body> </html>

Kết quả

The best e-learning platform is Tutorix The best e-learning platform is Tutorix


Dùng Template Strings ES6

Ví dụ

Dùng template strings (backtick `...${biến}...`). Mã ngắn gọn, dễ đọc hơn hẳn.

<html> <body> <script> 
    const platform = 'Tutorix'; 
    const templateString = `The best e-learning platform is ${platform}`; 
    document.write(templateString); 
</script> </body> </html>

Kết quả

The best e-learning platform is Tutorix