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.