ES6 的模板字串在 JavaScript 中的重要性是什麼?
ES6 的模板字串是一種新的字串組合方式。我們已有join()、concat()等方法來組合字串,但模板字串方法是最複雜的方法,因為它更易於讀取、無需使用反斜槓來轉義引號,也不再需要混亂的加法運算子。
使用 concat() 和 join()
示例
在以下示例中,使用join()和concat()方法來組合字串。如果我們仔細觀察,程式碼會顯得非常混亂。
<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>輸出
The best e-learning platform is Tutorix The best e-learning platform is Tutorix
使用 ES6 的模板字串
示例
在以下示例中,使用模板字串方法來組合字串。如果我們將此方法與其他方法進行比較,此方法中的程式碼非常簡明且易於閱讀。
<html>
<body>
<script>
const platform = 'Tutorix';
const templateString = `The best e-learning platform is ${platform}`;
document.write(templateString);
</script>
</body>
</html>輸出
The best e-learning platform is Tutorix
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP