ES6_使用模板文本(‘``’、‘${ }’)创建字符串

为了方便创建复杂灵活的字符串,用到了重音符:‘ `` ’(backtick),和 ‘ ${ } ’。

const person = {
  name: "Zodiac Hasbro",
  age: 56
};

const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;

console.log(greeting); //Hello, my name is Zodiac Hasbro! and I am 56 years old.

Firstly, the example uses backticks (`), not quotes (' or "), to wrap the string. Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting \n within strings. The ${variable} syntax used above is a placeholder. Basically, you won't have to use concatenation with the + operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with ${ and }. Similarly, you can include other expressions in your string literal, for example ${a + b}. This new way of creating strings gives you more flexibility to create robust strings.

首先,该示例使用重音符(`),不使用引号('或")来包装字符串。其次,请注意,字符串在代码和输出中都是多行的。这可以节省在字符串中插入的时间。上面使用的${variable}语法是占位符。基本上,您不必再使用加号运算符进行连接。要将变量添加到字符串中,只需将变量放入模板字符串中,并用${ }包装即可类似地,您可以在字符串文本中包含其他表达式,例如${a+b}。这种创建字符串的新方法为您创建健壮字符串提供了更大的灵活性。

再看例子:

const result = {
  success: ["max-length", "no-amd", "prefer-arrow-functions"],
  failure: ["no-var", "var-on-top", "linebreak"],
  skipped: ["no-extra-semi", "no-dup-keys"]
};
function makeList(arr) {
  const failureItems = [];
  for (let i=0; i<arr.length; i++) {
    failureItems.push(`<li class="text-warning">${arr[i]}</li>`);
  }
  return failureItems;
}

//测试:
const failuresList = makeList(result.failure);
console.log(failuresList);
/*控制台输出如下:
[ '<li class="text-warning">no-var</li>',
  '<li class="text-warning">var-on-top</li>',
  '<li class="text-warning">linebreak</li>' ]
*/

 

posted @ 2022-09-14 21:25  枭二熊  阅读(816)  评论(0编辑  收藏  举报