ES6功能:模板字符串如何有用? [英] ES6 Feature: How are Template Strings useful?

查看:103
本文介绍了ES6功能:模板字符串如何有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AKA模板文字,字符串插值。 ( Wiki here 。)

AKA Template Literals, String Interpolation. (Wiki here.)

为什么它们有用?

什么时候不应该使用它们?

When should I not use them?

这些功能与使用JSX和React的功能有何不同?

How are these features similar and different from using JSX with React?

我如何使用 String.raw()有效如维基的底部所述?

How can I use String.raw() effectively as mentioned in the bottom of the wiki?

推荐答案

字符串模板(或字符串插值)功能在许多编程语言中无处不在。如果您希望使用当前范围中的变量填充不同或重复的模板,则应使用它。它使模板比字符串的连接或 printf - 样式格式更具可读性。

The string templating (or string interpolation) feature is ubiquitous in many programming languages. You should use it when you have a distinct or recurring template that you wish to fill in with the variables in current scope. It makes the template more readable than concatenation of strings or printf-style formatting.

与JSX的区别在于JSX用于模板化HTML,而字符串模板用于模板化任何类型的文本,例如日志消息或用户输出。

The difference with JSX is that JSX is intended for templating HTML, whereas string templates are for templating any kind of text, for instance, log messages or user output.

当您希望对具有大量实际反斜杠但不转义反斜杠的字符串进行操作时,原始字符串可能很有用。例如,如果要描述字符串 \ n \\\000000 ,那么您可以将其写为 \\ n \\\\\0000 ,这不是很易读。使用原始字符串,您可以将其写为 String.raw('\ n \\\ 000000')

The raw strings may be useful when you wish to operate on a string that has a lot of actual backslashes, not escaping backslashes. For instance, if you want to describe a string \n\r\u0000, then you would write it as \\n\\r\\u0000, which is not very readable. With raw strings, you can write it as String.raw('\n\r\u0000').

这篇关于ES6功能:模板字符串如何有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆