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

更新於: 2019 年 7 月 30 日

111 次瀏覽

開啟你的 職業發展

透過學習本課程獲得認證

開始吧
廣告
© . All rights reserved.