ES6 Feature: How are Template Strings useful?

拟墨画扇 提交于 2019-12-07 17:31:43

问题


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

Why are they useful?

When should I not use them?

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

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


回答1:


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.

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.

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').




回答2:


They make the code more readable. For example:

// ES6
let fruit = 'apples'
console.log(`I like ${fruit}.`)

The ES5 equivalent:

// ES5
var fruit = 'apples'
console.log('I like ' + fruit + '.')

The multiline feature is also convenient for writing large blocks of words:

// ES6
console.log(`string text line 1
string text line 2`)

The ES5 equivalent:

// ES5
console.log("string text line 1\nstring text line 2")

Template strings should always be used if variables are present.




回答3:


That code is more readable without terminating strings and append variables.

var links = [{
  url: "http://www.google.com",
  name: "Google"
}, {
  url: "http://www.yahoo.com",
  name: "Yahoo"
}, {
  url: "http://www.bing.com",
  name: "Bing"
}];

var output = "<ul>";

for (var i = 0, len = links.length; i < len; i++) {

  output += `
      <li><a href="${links[i].url}">${links[i].name}</a></li>
   `;

}

output += "</ul>";
document.getElementById('output').innerHTML = output;
<div id="output">


</div>



回答4:


Use 1

It's multiline. (In JS, norm strings need backslashes before newline chars.)


Use 2

An alternative style. Compare:

a: ${a}, b: ${b}, c: ${c}, d: ${d}, e: ${e}

.with:

a: '+a+', b: '+b+', c: '+c+', d: '+d+', e: '+e

.And compare:

function generated_function(){
    '+ statement1 +'
    '+ function2_name +'();
    f3();
    f'+ 5*5 +'();
}

.with:

function generated_function(){
    ${statement1}
    ${function2_name}();
    f3();
    f${ 5*5 }();
}

Nicety

It's backslash-escaped too—<${> by <\${> or <$\{>.

Nb

It's different to <String.raw>. Cf §.

来源:https://stackoverflow.com/questions/30542657/es6-feature-how-are-template-strings-useful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!